Java MySQL prepareStatement批处理
作者:互联网
我正在尝试使用prepareStatement Batch,但是遇到问题.
以下代码不会给我错误,但是只会在表格中插入地图的最后一个键,我也不知道为什么.
这肯定是一个非常愚蠢的错误,但这是我第一次使用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();
标签:java,mysql,prepared-statement,batch-file 来源: https://codeday.me/bug/20191012/1902577.html