1 /** 2 * 快速入门 3 */ 4 @Test 5 public void demo1() { 6 /** 7 * * 1.加载驱动. 8 * * 2.获得连接. 9 * * 3.编写sql执行sql. 10 * * 4.释放资源. 11 */ 12 // 1.加载驱动: 13 // DriverManager.registerDriver(new Driver()); 14 // 查看源代码了 只要Driver类一加载,注册驱动. 15 Connection conn = null; 16 Statement stmt = null; 17 ResultSet rs = null; 18 try { 19 Class.forName("com.mysql.jdbc.Driver"); 20 // 2.获得连接: 21 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day17", "root", "123"); 22 // 3.执行sql. 23 // 3.1编写一个sql语句 24 String sql = "select * from user"; 25 // 3.2创建一个执行sql的对象. 26 stmt = conn.createStatement(); 27 // 3.3调用stmt中的方法执行sql语句 28 rs = stmt.executeQuery(sql); 29 // 3.4遍历结果集 30 while(rs.next()){ 31 int id = rs.getInt("id"); 32 String username = rs.getString("username"); 33 String password = rs.getString("password"); 34 System.out.println(id+" "+username+" "+password); 35 } 36 } catch (Exception e) { 37 e.printStackTrace(); 38 }finally{ 39 // 4.释放资源. 40 if (rs != null) { 41 try { 42 rs.close(); 43 } catch (SQLException sqlEx) { 44 // ignore } 45 } 46 47 rs = null; 48 } 49 50 if (stmt != null) { 51 try { 52 stmt.close(); 53 } catch (SQLException sqlEx) { 54 // ignore } 55 } 56 57 stmt = null; 58 } 59 60 if (conn != null) { 61 try { 62 conn.close(); 63 } catch (SQLException sqlEx) { // ignore } 64 65 } 66 // 手动设置为null. 67 conn = null; 68 } 69 } 70 }