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 block39 e.printStackTrace();40 } catch (SQLException e) {41 // TODO Auto-generated catch block42 //处理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 block51 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 block60 e.printStackTrace();61 }62 connection = null;63 }64 if(rs != null) {65 try {66 rs.close();67 } catch (Exception e2) {68 // TODO: handle exception69 }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"。