如何将准备好的语句与Apache DBUtils一起使用?

时间:2013-04-10 00:45:27

标签: java prepared-statement apache-commons-dbutils

准备好的语句如何与Apache DBUtils一起使用?

似乎org.apache.commons.dbutils。*的大多数方法都需要字符串参数。令人惊讶的是,没有一种方法可以接受PreparedStatements。

2 个答案:

答案 0 :(得分:5)

准备语句在DbUtils BUT中使用,准备语句的要点不是每次进行更新时都准备一个语句,并重用它只更改params。假设您必须插入1000条记录,您希望重用相同的预处理语句,仅更改参数。为此,请使用QueryRunner.batch而不是QueryRunner.update。

答案 1 :(得分:1)

来自examples page

// Execute the query and get the results back from the handler
Object[] result = run.query(
    "SELECT * FROM Person WHERE name=?", h, "John Doe");

表示必须使用PreparedStatement。在the source for the query method我们看到了

private <T> T query(Connection conn, boolean closeConn, String sql, 
                     ResultSetHandler<T> rsh, Object... params)
...
PreparedStatement stmt = null;
ResultSet rs = null;
T result = null;

try {
    stmt = this.prepareStatement(conn, sql);
    this.fillStatement(stmt, params);
    rs = this.wrap(stmt.executeQuery());
    result = rsh.handle(rs);
} catch (SQLException e) {
...

结论?正在使用PreparedStatement,无需担心。