你可能想在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