Welcome

首页 / 网页编程 / JSP / JSP程序使用JDBC连接MySQL的教程

安装和加载JDBC驱动程序
下载JDBC驱动程序mysql-connector-java-5.1.7.zip
http://www.jb51.net/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>