首页 > 开发 > JSP > 正文

JSP程序使用JDBC连接MySQL的教程

2019-10-27 18:00:26
字体:
来源:转载
供稿:网友
这篇文章主要介绍了JSP程序使用JDBC连接MySQL的教程,简单地来搭建Tomcat+JSP(Java)+MySQL的生产环境,需要的朋友可以参考下
 

安装和加载JDBC驱动程序

下载JDBC驱动程序mysql-connector-java-5.1.7.zip
http://www.cuoxin.com/softs/214141.html
将里面的文件mysql-connector-java-5.1.7-bin.jar放在项目WEB-INF目录下的lib文件中,安装就已经完成了(前提是你的机器已经安装了MySQL,如果没有安装先安装)

加载在JDBC驱动程序

<%@page language="java" contentType="text/html;charset=gb2312"%><!DOCTYPE html><html>  <head>    <title>加载JDBC驱动程序</title>  </head>  <body>    <%      try{        Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动程序      }catch(ClassNotFoundException e){        out.println("找不到驱动类");//抛出异常时,提示信息      }    %>  </body></html>

连接MySQL数据库
启动Mysql和Tomcat,

使用JDBC连接数据库。

第一种方式

<%@page language="java" contentType="text/html;charset=gb2312"%><%@page import="java.sql.*" %><!DOCTYPE html><html>  <head>    <title>链接MySQL数据库</title>  </head>  <body>    <%      try{        Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动程序        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaweb?user=root&password=zhangda890126;;");//链接数据库               }catch(ClassNotFoundException e){        out.println("找不到驱动类");//抛出异常时,提示信息      }catch(SQLException e){        out.println("链接MySQL数据库失败");//处理SQLException异常      }    %>  </body></html>

第二种方式

<%@page language="java" contentType="text/html;charset=gb2312"%><%@page import="java.sql.*" %><!DOCTYPE html><html>  <head>    <title>链接MySQL数据库</title>  </head>  <body>    <%      String url = "jdbc:mysql://localhost:3306/javaweb";//连接数据库的url地址      String user = "root";//登录数据库的用户名      String password = "zhangda890126;;";//登录数据库的用户名的密码      try{        Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动程序        Connection conn = DriverManager.getConnection(url,user,password);//链接数据库               }catch(ClassNotFoundException e){        out.println("找不到驱动类");//抛出异常时,提示信息      }catch(SQLException e){        out.println("链接MySQL数据库失败");//处理SQLException异常      }    %>  </body></html>


注:相关教程知识阅读请移步到JSP教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表