JDBC寫成工具類

2021-09-10 09:20:20 字數 2215 閱讀 8587

public class jdbcutils  catch (classnotfoundexception e) 

}public static connection getconnection() throws exception

public static void closeall(connection con,statement st,resultset rs) catch (sqlexception e)

} if(st != null) catch (sqlexception e)

} if(rs != null) catch (sqlexception e) }

}

public class test 

} catch (exception e) finally}}

要用preparestatement

例子:string sql=「select * from 表名 where cid=? and name=?」;

//先預處理

preparestatement ps=con.preparestatement(sql)

//把上面?的地方,替換掉(第幾個"?"序號從1開始,替換的值)

ps.setobject(1, 替換的值);

ps.setobject(2, 替換的值);

//建立結果集

rs = ps.executequery();

public class test02 		

public static void zeng()catch(exception e)finally

} public static void shan()catch(exception e)finally

} public static void gai()catch(exception e)finally

} public static void cha()

}catch(exception e)finally

}}

這裡棄用createstatement,因為會sql注入

//輸入賬號密碼

scanner sc = new scanner(system.in);

system.out.println("賬號");

string zhanghao=sc.nextline();

system.out.println("密碼");

string mima=sc.nextline();

connection con = null;

preparedstatement ps = null;

resultset rs = null;

try else

} catch (exception e)

//釋放資源

tools.closeall(con, ps, rs);

好處:不需要在工具類中改動資料庫資訊1.寫乙個配置檔案

1.新建乙個檔案config.properties

2.寫入資料庫資訊

url=jdbc:mysql://localhost:3306/product

driver=com.mysql.jdbc.driver

user=root

password=root

2.修改工具類中的**

public class tools  catch (exception e) 				}	

public static connection lianjie() throws exception

public static void closeall(connection con,statement st,resultset rs) catch (sqlexception e)

} if(st !=null) catch (sqlexception e)

} if(rs !=null) catch (sqlexception e)

} }}

JDBC工具類封裝

jdbc之工具類封裝 編寫工具類步驟 1 將固定字串定義為常量 2 由於工具類的方法都是靜態,因此註冊驅動可以放在靜態 塊中 3 提供獲取連線物件的方法connection getconnection 4 提供關閉資源的方法close resultset rs,statement stmt,conn...

jdbc事務工具類

工具類 提供資料庫連線池 和資料庫連線 public class jdbcutils 當dbutils需要手動控制事務時,呼叫該方法獲得乙個連線 public static connection getconnection throws sqlexception public class trans...

JDBC工具類的建立

1.配置檔案 在src下建立config.properties 2.建立私有構造方法 要與類名一致 3.宣告配置資訊變數 用於properties讀取配置檔案中的資訊 4.建立靜態 塊 實現載入配置檔案和註冊驅動 通過類載入器返回配置檔案的位元組流 建立properties集合,載入流物件的資訊 註...