【问题标题】:Add multiple Prepared Statements in Java sql在Java sql中添加多个Prepared Statements
【发布时间】:2012-11-20 08:22:22
【问题描述】:

我有多个要同时执行的 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;
    }

最初,我尝试将这些添加到向量/数组并一次执行一个,但由于结果集和索引的复杂性,我不断收到“jdbc4.MySQLNonTransientConnectionException:语句关闭后不允许操作”

然后我考虑将所有语句添加到一个批处理中并立即执行。当然,addBatch() 需要一个字符串而不是 PreparedStatement 作为参数。当我在这个网站上搜索时,我找到了这个答案:How to generate String "elegantly" in Java?,它建议构建和格式化字符串以添加到批处理中,这会使代码容易受到 SQL 注入攻击。

那么,有没有替代这两种方法来一次执行多个查询?如果没有,以上哪个更可取,为什么?

【问题讨论】:

标签: java sql string batch-file prepared-statement


【解决方案1】:

有多个addBatch 方法。

你应该和你一样设置你的参数,然后使用PreparedStatement声明的void addBatch()

【讨论】:

    猜你喜欢
    • 2013-05-05
    • 2014-04-14
    • 1970-01-01
    • 2012-08-23
    • 2013-08-25
    • 2016-02-19
    • 2016-10-25
    • 2011-11-28
    • 2015-09-03
    相关资源
    最近更新 更多