2013-04-10 75 views
0

如何預處理語句與Apache DBUtils使用嗎?準備好的語句如何與Apache DBUtils一起使用?

似乎大多數爲org.apache.commons.dbutils的方法。*期望字符串參數。令人驚訝的是沒有接受PreparedStatements的方法。

+0

看看[QueryRunner的源代碼](http://svn.apache.org/viewvc/commons/proper/dbutils/trunk/src/main/java/org/apache/commons/dbutils/QueryRunner.java ?view =標記),你會注意到它們(查看'query','update'和'insert'的主要實現)。或者你想喂這些方法現有的'PreparedStatement'實例嗎? – fvu 2013-04-10 00:54:46

+0

是的,我注意到了。這對我來說有點過分了,所以我正在努力。我以前使用Prepared Statements,但不使用這些QueryRunner方法。這就是我想要做的,所以當我處理我的表單輸入時,它不會與撇號崩潰。 – VisWebsoft 2013-04-10 12:55:18

回答

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,根本不需要擔心。

+0

得到它的工作。感謝您指出正確的方向。 – VisWebsoft 2013-04-13 04:03:33

4

預處理語句用於內部DbUtils,但事先準備好的聲明的一點是不要每次做一個更新時間準備的聲明中,並重新使用它只是改變了PARAMS。假設你必須插入1000條記錄,你想重複使用相同的準備語句只更改params。爲此,請使用QueryRunner.batch而不是QueryRunner.update。

+0

但是,如果插入了一百萬條記錄,我很懷疑自從QueryRunner.batch初始化準備好的語句以來,dbutils將成爲解決方案。我建議編寫一個自定義的實現,而不是訴諸於dbutils。我不確定是否有任何其他緩存準備好的語句的工具。 – dmachop 2016-06-28 16:13:11