java连接数据库测试

 1 import java.sql.DriverManager;
 2 import java.sql.ResultSet;
 3 import java.sql.SQLException;
 4 
 5 import com.mysql.jdbc.Connection;
 6 import com.mysql.jdbc.Statement;
 7 
 8 
 9 public class JDOBC {
10     
11  
12     public void jdobc() {
13         final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
14         final String DB_URL = "jdbc:mysql://localhost:3306/bruceproject";
15      
16         // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
17         //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
18         //static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
19      
20      
21         // 数据库的用户名与密码,需要根据自己的设置
22         final String USER = "root";
23         final String PASS = "123456";
24     
25         java.sql.Connection conn = null;
26         java.sql.Statement stmt = null;
27         try{
28             // 注册 JDBC 驱动
29             Class.forName(JDBC_DRIVER);
30         
31             // 打开链接
32             System.out.println("连接数据库...");
33             conn = DriverManager.getConnection(DB_URL,USER,PASS);
34         
35             // 执行查询
36             System.out.println(" 实例化Statement对象...");
37             stmt = conn.createStatement();
38             String sql;
39             sql = "SELECT id, name, age FROM student";
40             ResultSet rs = stmt.executeQuery(sql);
41         
42             // 展开结果集数据库
43             while(rs.next()){
44                 // 通过字段检索
45                 int id  = rs.getInt("id");
46                 String name = rs.getString("name");
47                 int age = rs.getInt("age");
48     
49                 // 输出数据
50                 System.out.print("ID: " + id);
51                 System.out.print(", 名称: " + name);
52                 System.out.print(", 年龄: " + age);
53                 System.out.print("\n");
54             }
55             // 完成后关闭
56             rs.close();
57             stmt.close();
58             conn.close();
59         }catch(SQLException se){
60             // 处理 JDBC 错误
61             se.printStackTrace();
62         }catch(Exception e){
63             // 处理 Class.forName 错误
64             e.printStackTrace();
65         }finally{
66             // 关闭资源
67             try{
68                 if(stmt!=null) stmt.close();
69             }catch(SQLException se2){
70             }// 什么都不做
71             try{
72                 if(conn!=null) conn.close();
73             }catch(SQLException se){
74                 se.printStackTrace();
75             }
76         }
77         System.out.println("Goodbye!");
78     }
79 }
JDOBC

Java 连接 MySQL 需要驱动包,最新版下载地址为:http://dev.mysql.com/downloads/connector/j/,解压后得到 jar 库文件,然后在对应的项目中导入该库文件。

 

具体文件看下面连接

https://www.runoob.com/java/java-mysql-connect.html

 

posted @ 2021-09-23 11:25  Bruce_Sun  阅读(259)  评论(0)    收藏  举报