2012-12-02 39 views
1

我有多個SQL準備好的語句要同時執行。到現在爲止,我一直在使用,看起來或多或少像這樣一份準備好的聲明方法:在Java中添加多個準備好的語句sql

public PreparedStatement createWordEntry(Connection c, String word, String word2, int num) throws SQLException{ 
     PreparedStatement entry = c.prepareStatement("INSERT INTO table VALUES(?,?,?)"); 
     entry.setString(1, word); 
     entry.setString(2, word2); 
     entry.setInt(3,num); 
     return entry; 
    } 

本來,我嘗試添加這些爲矢量/陣列,並執行它們一次一個,但由於複雜的與resultSets和索引,我不斷收到「jdbc4.MySQLNonTransientConnectionException:語句關閉後沒有任何操作允許」

然後,我看着將所有語句添加到批處理,並立即執行。當然,addBatch()需要一個字符串,而不是PreparedStatement作爲參數。當我在這個網站上搜索時,我發現這個答案:How to generate String "elegantly" in Java?它建議構建和格式化字符串以添加到容易受SQL注入攻擊影響的批處理葉代碼。

那麼,這兩種方法是否可以同時執行多個查詢?如果沒有,上面哪一個更可取,爲什麼?

+1

[批量更新](http://www.mkyong.com/jdbc/jdbc-preparedstatement-example-batch-update/) –

+1

您可以**在批處理模式下使用PreparedStatement,請參閱http:// stackoverflow .com/questions/4392091/preparedstatement-addbatch-in-java-has-any-restrictions for some hints。 – RealHowTo

回答

0

有多種addBatch方法。

您應該像您一樣設置參數,然後使用PreparedStatement聲明的void addBatch()