你可能想在Apache的共享庫類似的DbUtils包:http://commons.apache.org/dbutils/index.html][1]
的QueryRunner類,您可以執行SQL語句,而無需手動創建的PreparedStatement,甚至有一個開放的連接物。從實例頁:
QueryRunner run = new QueryRunner(dataSource);
try
{
// Create an object array to hold the values to insert
Object[] insertParams = {"John Doe", new Double(1.82)};
// Execute the SQL update statement and return the number of
// inserts that were made
int inserts = run.update("INSERT INTO Person (name,height) VALUES (?,?)",
insertParams);
// Now it's time to rise to the occation...
Object[] updateParams = {new Double(2.05), "John Doe"};
int updates = run.update("UPDATE Person SET height=? WHERE name=?",
updateParams);
}
catch(SQLException sqle) {
// Handle it
}
因此,它基本上處理的預處理語句創建透明,你真的需要知道的唯一事情是一個數據源。這也適用於非更新/插入語句,即簡單香草選擇查詢,並且創建ResultSetHandlers的能力使您能夠將ResultSet轉換爲類似完全準備的bean或具有鍵的Map是列名稱,值是實際的行值。當您無法實施整個ORM解決方案時非常有用。
您的executeNonQuery方法有一個問題:獲取連接。如果每次執行此方法時都創建一個,則會反覆執行性能問題(創建和關閉連接很昂貴)。如果這封裝在僅在首次調用時創建連接的對象上,則會出現問題:什麼時候關閉它?也許基於時間?如果您使用靜態字段進行緩存,請注意不會收集。不過,在緩存連接時,要小心併發調用:如果沒有鎖定機制(例如syncrhonized),則可以創建大量連接。 – 2009-06-08 15:18:07