2012-12-02 40 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()