Java MySQL prepareStatement批处理 [英] Java MySQL preparedStatement Batch

查看:48
本文介绍了Java MySQL prepareStatement批处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用prepareStatement Batch,但是遇到问题.

I am trying to use the preparedStatement Batch but I am having a problem.

以下代码不会给我错误,但是它仅将表的最后一个键插入表中,我不知道为什么.

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.

这肯定是一个非常愚蠢的错误,但这是我第一次使用addBatch()方法.

It will be surely a very stupid error, but this is the first time I use the addBatch() method..

        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();

提前谢谢!

推荐答案

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

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();

这篇关于Java MySQL prepareStatement批处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆