JDBC的学习(一)--Java与MySQL的连接

 1 package cn.yn.text0;
 2 
 3 import java.sql.*;
 4 
 5 public class TextJdbc1{
 6     //JDBC驱动名以及数据库URL
 7     static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
 8     static final String DB_URL = "jdbc:mysql://localhost:3306/textjdbc?serverTimezone=GMT";
 9     //数据库的用户名以及密码
10     static final String USER = "root";
11     static final String PWD = "123";
12     public static void main(String[] args) {
13         Connection connection = null;
14         Statement statement = null;
15         ResultSet rs = null;
16         try {
17             //1、加载驱动
18             Class.forName("com.mysql.cj.jdbc.Driver");
19             //2、打开链接
20             System.out.println("正在连接到数据库。。。");
21             connection = DriverManager.getConnection(DB_URL, USER, PWD);
22             //3、查询
23             statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
24             rs = statement.executeQuery("select * from tb_user");
25             
26             //循环取出
27             while(rs.next()) {
28                 System.out.println("编号"+rs.getInt(1)+"姓名"+rs.getString(2));
29             }
30             //如果我还是想重新使用游标
31             rs.absolute(2);
32             System.out.println("*****************************");
33             while(rs.next()) {
34                 System.out.println("编号"+rs.getInt(1)+"姓名"+rs.getString(2));
35             }
36             
37         } catch (ClassNotFoundException e) {
38             // TODO Auto-generated catch block
39             e.printStackTrace();
40         } catch (SQLException e) {
41             // TODO Auto-generated catch block
42             //处理jdbc错误
43             e.printStackTrace();
44         }finally {
45             //关闭资源
46             if(statement != null) {
47                 try {
48                     statement.close();
49                 } catch (SQLException e) {
50                     // TODO Auto-generated catch block
51                     e.printStackTrace();
52                 }
53                 statement = null;//垃圾回收
54             }
55             if(connection  != null) {
56                 try {
57                     connection.close();
58                 } catch (SQLException e) {
59                     // TODO Auto-generated catch block
60                     e.printStackTrace();
61                 }
62                 connection = null;
63             }
64             if(rs != null) {
65                 try {
66                     rs.close();
67                 } catch (Exception e2) {
68                     // TODO: handle exception
69                 }
70             }
71         }
72     }
73 }

其中使用MySQL-connector-Java-8.0 的jar包时,JDBC_DRIVER为"com.mysql.cj.jdbc.Driver",DB_URL为 "jdbc:mysql://localhost:3306/textjdbc?serverTimezone=GMT"。

猜你喜欢

转载自www.cnblogs.com/nick9527/p/9355123.html