JAVA-数据库之JDBC连接MySQL数据库

相关资料:
《21天学通Java Web开发》

JDBC连接MySQL数据库
1.如果需要通过JDBC来连接MySQL数据库,还必须先在MySQL数据库服务器中创建数据库和表。

ConnectionDemo.jsp

 1 <%@ page language="java" contentType="text/html; charset=gb2312" %>
 2 <%@ page import="java.sql.*"%>
 3 <html>
 4 <head>
 5   <title>连接MYSQL数据库</title>
 6 </head>
 7 <body>
 8   <%
 9     try{
10       Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动程序
11       Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/java?user=root&password=zhujq");
12       out.println("连接数据库成功!");
13       }catch(ClassNotFoundException e){
14         out.println("找不到驱动类");
15       }catch(SQLException e){
16       out.println("连接SQL数据库失败");
17       }            
18   %>
19 </body>
20 </html>
View Code

ConnectionDemo2.jsp

 1 <%@ page language="java" contentType="text/html; charset=gb2312" %>
 2 <%@ page import="java.sql.*"%>
 3 <html>
 4 <head>
 5   <title>连接MYSQL数据库</title>
 6 </head>
 7 <body>
 8   <%
 9     String url = "jdbc:mysql://localhost:3306/java";
10     String user = "root";
11     String password = "zhujq";
12     try{
13       Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动程序
14       Connection conn= DriverManager.getConnection(url, user, password);
15       out.println("连接数据库成功!");
16       }catch(ClassNotFoundException e){
17         out.println("找不到驱动类");
18       }catch(SQLException e){
19       out.println("连接SQL数据库失败");
20       }      
21   %>
22 </body>
23 </html>
View Code
原文地址:https://www.cnblogs.com/FKdelphi/p/7670967.html