一:將查詢的結果生成對象,儲存在數組中。
1 package day31; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.util.ArrayList; 8 9 public class java_obj { 10 public static void main(String[] args)throws SQLException{ 11 Connection con=jdbcutils.getCon(); 12 PreparedStatement pst=con.prepareStatement("select * from system_user"); 13 ResultSet res=pst.executeQuery(); 14 /* 15 將查詢的結果用泛型數組儲存。 16 */ 17 ArrayList<System_user> sys_list=new ArrayList<>(); 18 while (res.next()){ 19 System_user sys_u=new System_user(res.getString("username"),res.getString("password")); 20 sys_list.add(sys_u); 21 } 22 System.out.print(sys_list); 23 jdbcutils.cls_re(con,pst,res); 24 } 25 } 26 27 28 class System_user{ 29 private String user; 30 private String pwd; 31 public System_user(String user, String pwd){ 32 this.user=user; 33 this.pwd=pwd; 34 } 35 36 @Override 37 public String toString() { 38 return this.user+" "+this.pwd; 39 } 40 }
?工具類:
1 package day31; 2 3 import java.sql.*; 4 5 public class jdbcutils { 6 /* 7 創建jdbc工具類。 8 1:方便別人調用 9 2:避免代碼重復。 10 */ 11 private jdbcutils(){}//工具類不需要實例化,所以方法進行私有化。 12 private static Connection con;//需要靜態變量 13 14 /* 15 靜態代碼塊在加載類的時候就執行該部分的代碼。 16 */ 17 static { 18 try{ 19 Class.forName("com.mysql.jdbc.Driver"); 20 String url="jdbc:mysql://192.168.147.146:3306/homework_day13"; 21 String username="test"; 22 String password="123456"; 23 con= DriverManager.getConnection(url,username,password); 24 }catch (Exception ex){ 25 throw new RuntimeException(ex+"數據庫連接失敗!");//如果出現異常的話 需要種子程序 所以要拋出異常。需要創建運行異常的錯誤。 26 } 27 } 28 29 public static Connection getCon(){ 30 return con; 31 } 32 /* 33 關閉資源。 34 通過方法的重載來判斷用戶執行的是查詢和更新操作。 35 */ 36 public static void cls_re (Connection con, Statement pst, ResultSet rs)throws SQLException{ 37 /* 38 注意:這里需要判斷需要關閉的對象是否存在以及該對象如果拋出異常不能影響下面的關閉。 39 這里是Statement 是prepareStament的父類。 40 */ 41 if(con!=null){ 42 try { 43 con.close(); 44 }catch (Exception ex){} 45 } 46 if(pst!=null){ 47 try { 48 pst.close(); 49 }catch (Exception ex){} 50 } 51 if(rs!=null){ 52 try { 53 rs.close(); 54 }catch (Exception ex){} 55 } 56 57 } 58 public static void cls_re(Connection con,Statement pst){ 59 if(pst!=null){ 60 try { 61 pst.close(); 62 }catch (Exception ex){} 63 } 64 if(pst!=null){ 65 try { 66 pst.close(); 67 }catch (Exception ex){} 68 } 69 } 70 }
?