Question

How can Prepared Statements be used with Apache DBUtils?

It seems that most of the methods for org.apache.commons.dbutils.* expect string arguments. It's surprising that there isn't a method that accepts PreparedStatements.

Was it helpful?

Solution 2

From the 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");

which indicates that there must be a PreparedStatement being used. And in the source for the query method we see

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) {
...

Conclusion? PreparedStatements are being used, no need to be worried at all.

OTHER TIPS

Prepared Statements is used inside DbUtils BUT, the point of prepared statement is not to prepare a statement each time you do an update, and reuse it changing only the params. Suppose you have to insert 1000 records, you'd like to reuse the same prepared statement changing only the params. To do so, use QueryRunner.batch instead of QueryRunner.update.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top