顯示具有 JDBC 標籤的文章。 顯示所有文章
顯示具有 JDBC 標籤的文章。 顯示所有文章

2007年1月9日 星期二

利用 PreparedStatement 批次查詢

平常StatementPreparedStatement的executeUpdate()的方法只能執行一個SQL敘述, 如果有很多SQL要執行的話,就得用addBatch()executeBatch()

ex1.

String strqry="insert into test (col1,col2) values (?,?)";
PreparedStatement pstmt = con.prepareStatement(strqry);
pstmt.setString(1,"test1");
pstmt.setString(2, "123");
pstmt.addBatch();
pstmt.setString(1,"test2");
pstmt.setString(2, "456");
pstmt.addBatch();
pstmt.executeBatch();

ex2:

Statement stmt=con.createStatement();
stmt.addBatch("insert into test (col1,col2) values ('test1','123')");
stmt.addBatch("update test set col2='789' where col1='test4'");
stmt.executeBatch();

2006年11月16日 星期四

JDBC 實務:使用 JDBC 時,一定要放在 try 區塊中,並於 finally 區塊釋放 Connection

在 try/catch/finally 語法中,若有定義 finally 區塊,則執行 try 區塊後,一定會執行 finally 區塊的程式碼。
所以若程式有使用 JDBC 時,一定要包在 try 區塊中,並在 finally 中關閉 connection 釋放資源,才不會耗盡資源。
一般實務作法如下例:


Connection con=null;
try{
con=new Connection();
...
...
...
}finally{
try{
con.close();
}catch(Throwable e) {
String errmsg="close connection failed! errmsg is "+e.getMessage();
log.error(errmsg);
}
}