简体   繁体   English

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

[英]Add multiple Prepared Statements in Java sql

I have multiple SQL prepared statements I want to execute at the same time. 我有多个要同时执行的SQL准备语句。 Up until now, I had been using a prepared statement method that looks more or less like this: 到现在为止,我一直在使用一种准备的语句方法,该方法或多或少看起来像这样:

    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;
    }

Originally, I tried adding these to a vector / array and executing them one at a time, but because of intricacies with resultSets and indexing, I kept getting "jdbc4.MySQLNonTransientConnectionException: No operations allowed after statement closed" 最初,我尝试将它们添加到向量/数组中并一次执行一次,但是由于resultSet和索引的复杂性,我一直得到“ jdbc4.MySQLNonTransientConnectionException:语句关闭后不允许执行任何操作”

Then I looked into adding all statements into a batch and executing at once. 然后,我考虑将所有语句添加到批处理中并立即执行。 Of course, addBatch() requires a string as opposed to a PreparedStatement as a parameter. 当然,addBatch()需要一个字符串,而不是PreparedStatement作为参数。 When I searched on this site, I found this answer: How to generate String "elegantly" in Java? 在该站点上搜索时,我找到了以下答案: 如何在Java中“优雅地”生成String? which suggests building and formatting strings to add to a batch leaves code vulnerable to SQL injection attacks. 这建议构建和格式化字符串以添加到批处理中,使代码容易受到SQL注入攻击。

So, is there an alternative to these two methods for executing multiple queries at once? 那么,这两种方法是否可以替代一次执行多个查询? If there isn't, which of the above is preferable, and why? 如果没有,那么上面的哪一个更可取,为什么?

There are multiple addBatch methods. 有多种addBatch方法。

You should set your parameters the same way as you do, and then use void addBatch() declared by PreparedStatement . 您应该以与您相同的方式设置参数,然后使用PreparedStatement声明的void addBatch()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM