標籤:style blog io color os 使用 sp for 檔案
使用properties檔案設定資料庫驅動,uri,使用者名稱和密碼;以便於日後更換資料庫不用更改原始碼;
driver=com.mysql.jdbc.Driveruri=jdbc:mysql://localhost:3306/day10user=rootpassword=root
1.註冊驅動
1 public static Connection getConn() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{2 3 Class.forName(prop.getProperty("driver"));4 return DriverManager.getConnection(prop.getProperty("uri"),prop.getProperty("user"),prop.getProperty("password"));5 6 7 }
2.建立連接器
Connection conn = JDBCUtils.getConn();//Connection conn = DriverMananger("uri,user,password");
3.擷取傳輸器
Statment stat = conn.createStatement();
5.利用傳輸器查詢語句,並返回結果集
stat.executeUpdate(sql); 增刪改
stat.executeQuery(sql);查詢語句
6.關閉資源
1 public static void close(Connection conn,Statement stat,ResultSet rs){ 2 3 if(rs!=null){ 4 try { 5 rs.close(); 6 } catch (SQLException e) { 7 throw new RuntimeException(e); 8 9 }finally{10 rs=null;11 }12 }13 if(stat!=null){14 try {15 stat.close();16 } catch (SQLException e) {17 throw new RuntimeException(e);18 19 }finally{20 stat=null;21 }22 }23 if(conn!=null){24 try {25 conn.close();26 } catch (SQLException e) {27 throw new RuntimeException(e);28 29 }finally{30 conn=null;31 }32 }33 }
使用mysql(6部曲)