安裝和載入JDBC驅動程式
將裡面的檔案mysql-connector-java-5.1.7-bin.jar放在專案WEB-INF目錄下的lib檔案中,安裝就已經完成了(前提是你的機器已經安裝了MySQL,如果沒有安裝先安裝)
載入在JDBC驅動程式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <%@page language= "java" contentType= "text/html;charset=gb2312" %>
<!DOCTYPE html>
<html>
<head>
<title>加载JDBC驱动程序</title>
</head>
<body>
<%
try {
Class.forName( "com.mysql.jdbc.Driver" );
} catch (ClassNotFoundException e){
out.println( "找不到驱动类" );
}
%>
</body>
</html>
|
登入後複製
連接MySQL資料庫
啟動Mysql和Tomcat,
使用JDBC連接資料庫。
第一種方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <%@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" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/javaweb?user=root&password=zhangda890126;;" );//链接数据库
} catch (ClassNotFoundException e){
out.println( "找不到驱动类" );
} catch (SQLException e){
out.println( "链接MySQL数据库失败" );
}
%>
</body>
</html>
|
登入後複製
第二種方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <%@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" );
Connection conn = DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException e){
out.println( "找不到驱动类" );
} catch (SQLException e){
out.println( "链接MySQL数据库失败" );
}
%>
</body>
</html>
|
登入後複製
更多JSP程式使用JDBC連接MySQL的教學相關文章請關注PHP中文網!