[英]Java MySQL preparedStatement Batch
我正在嘗試使用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();
您使用的addBatch()方法錯誤。 在您的代碼中,您需要在for循環的每次迭代中執行prepareStatement,並且每次都會替換准備好的查詢。
每批只能調用一次prepareStatement。 您應該將准備好的語句放在循環之前(僅一個調用)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.