在Java sql中添加多个准备好的语句

在Java sql中添加多个准备好的语句,java,sql,string,batch-file,prepared-statement,Java,Sql,String,Batch File,Prepared Statement,我想同时执行多个SQL语句。到目前为止,我一直在使用一个prepared statement方法,它看起来或多或少像这样: public PreparedStatement createWordEntry(Connection c, String word, String word2, int num) throws SQLException{ PreparedStatement entry = c.prepareStatement("INSERT INTO table

我想同时执行多个SQL语句。到目前为止,我一直在使用一个prepared statement方法,它看起来或多或少像这样:

    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;
    }
最初,我尝试将它们添加到向量/数组中,并一次执行一个,但由于结果集和索引的复杂性,我一直得到jdbc4.MySQLNonTransientConnectionException:语句关闭后不允许执行任何操作

然后,我考虑将所有语句添加到一个批处理中,并立即执行。当然,addBatch需要字符串作为参数,而不是PreparedStatement。当我在这个网站上搜索时,我发现了这个答案:这意味着构建和格式化字符串以添加到批处理中,使得代码容易受到SQL注入攻击

那么,对于同时执行多个查询,除了这两种方法之外,还有其他方法吗?如果没有,上面哪一个更可取,为什么?

有多种addBatch方法

您应该以与设置参数相同的方式设置参数,然后使用PreparedStatement声明。

您可以在批处理模式下使用PreparedStatement,有关提示,请参阅。