简体   繁体   English

Java MySQL prepareStatement批处理

[英]Java MySQL preparedStatement Batch

I am trying to use the preparedStatement Batch but I am having a problem. 我正在尝试使用prepareStatement Batch,但是遇到问题。

The following code does not give me errors, but it inserts in the table only last key of the map and I do not know why. 以下代码不会给我错误,但是只会在表格中插入地图的最后一个键,我也不知道为什么。

It will be surely a very stupid error, but this is the first time I use the addBatch() method.. 这肯定是一个非常愚蠢的错误,但这是我第一次使用addBatch()方法。

        Class.forName("com.mysql.jdbc.Driver");
        this.connect = DriverManager.getConnection("jdbc:mysql://localhost/" + this.database + "?user=" + this.user + "&password=" + this.password);
        String s;
        for (String key : this.map.keySet())
        {
            s = ("insert into " + this.database + ".user (nickname) values (?)");
            this.preparedStatement = this.connect.prepareStatement(s);
            this.preparedStatement.setString(1, key);
            this.preparedStatement.addBatch();
        }

        this.preparedStatement.executeBatch();

Thanks in advance! 提前致谢!

Prepare your Statement and query outside of the loop: 在循环外准备语句和查询:

      s = ("insert into " + this.database + ".user (nickname) values (?)");
      this.preparedStatement = this.connect.prepareStatement(s);
      for (String key : this.map.keySet())
        {
            this.preparedStatement.setString(1, key);
            this.preparedStatement.addBatch();
        }
        this.preparedStatement.executeBatch();

You are using the addBatch() method wrong. 您使用的addBatch()方法错误。 In your code you are doing the prepareStatement in each iteration of for loop, and this replaces the prepared query each time. 在您的代码中,您需要在for循环的每次迭代中执行prepareStatement,并且每次都会替换准备好的查询。

You should only be calling prepareStatement once per batch. 每批只能调用一次prepareStatement。 You should place the prepared statement before the loop (only one call) 您应该将准备好的语句放在循环之前(仅一个调用)

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

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