JDBC鏈接MySQL,增刪改查方法

1.加載驅動
Class.forName();
參數爲"com.mysql.jdbc.Driver"
Mysql 5.8版本 8.0版本jar包
參數爲"com.mysql.cj.jdbc.Driver"
2.創建鏈接
URL=「jdbc:mysql://localhost:3306/databases」;
UserName = 「root」;
PassWrod=「123456」;
Connection con = DriverManager.getConnection(url,username,password);
3.查詢方法
public static ResultSet exeQuery(String sql,Object[] params){
//1.獲取鏈接
Connection con = getCon();
//2.實例PreparedStatement對象
PreparedStatement pst = con.PrepareStatement(sql);
//3.預編譯,遍歷數組
for(int i=0;i<params.length;i++){
//4.由於不知道字段是什麼類型 因此setObject類型
//5.下標是從0開始 因此i+1
pst.setObject(i+1,params[i]);
}
//6.執行查詢,返回ResultSet 結果集
ResultSet rs = pst.executeQuery();// 方法中不加sql參數,在實例化時參數已經傳過
//7.執行完返回值爲ResultSet類型
return rs;
}
4.增刪改通用方法
public static int exeUpdate(String sql,Object[] params){
//1.獲取鏈接
Connection con = getCon();
try{
//2.實例PreparedStatement對象
PreparedStatement pst = con.prepareStatement(sql); PreparedStatement pst = con.prepareStatement(sql);
//3.預編譯,遍歷數組 //3.預編譯,遍歷數組
for(int i=0;i<params.length;i++){ for(int i=0;i<params.length;i++){
//4.由於不知道字段是什麼類型 因此setObject類型
//5.下標是從0開始 因此i+1
pst.setObject(i+1,params[i]);
}
//6.返回值是int類型,表示受影響的記錄條數
pst.executeUpdate();
} catch(Exception e){
e.printStackTrace();
}finally{
//7.關閉鏈接釋放資源
closeAll();
}
return 0;
}
//釋放資源的方法 須要把PreparedStatement,ResultSet,Connection設置爲成員變量
public static void closeAll(){
try{
if(rs!=null){
rs.close();
}
if(pst!=null){
pst.close();
}
if(con!=null){
con.close();
}
}catch(Execption e){
e.printStackTrace();
}
}
mysql