安装和加载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>
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!