Java MySQL preparedStatement批处理

Java MySQL preparedStatement批处理,java,mysql,batch-file,prepared-statement,Java,Mysql,Batch File,Prepared Statement,我正在尝试使用preparedStatement批处理,但遇到问题 下面的代码没有给我错误,但它只在表中插入了映射的最后一个键,我不知道为什么 这肯定是一个非常愚蠢的错误,但这是我第一次使用addBatch()方法 Class.forName("com.mysql.jdbc.Driver"); this.connect = DriverManager.getConnection("jdbc:mysql://localhost/" + this.database +

我正在尝试使用preparedStatement批处理,但遇到问题

下面的代码没有给我错误,但它只在表中插入了映射的最后一个键,我不知道为什么

这肯定是一个非常愚蠢的错误,但这是我第一次使用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();

提前谢谢

准备语句并在循环外查询:

      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();
您使用的addBatch()方法错误。在代码中,您在for循环的每个迭代中都执行prepareStatement,每次都会替换准备好的查询


每批只能调用一次prepareStatement。您应该将准备好的语句放在循环之前(只有一个调用)

没有充分的理由将“connect”和“preparedStatement”作为成员变量。所要做的就是引入线程不安全性和其他错误的范围。使它们成为局部变量。@EJP是的,我从一个示例中获取了部分代码。。当我对它更有信心时,我会纠正它。谢谢你的建议!谢谢现在它工作了!现在我有另一个关于批处理的问题,我将打开另一个问题!请几分钟后看一看!:)