【问题标题】:Modified: How to update multiple rows in java jdbc on duplicate value修改:如何更新java jdbc中重复值的多行
【发布时间】:2017-02-27 14:20:49
【问题描述】:

我有一个带有多个复选框的 .jsp 页面。我可以插入多个复选框值,但是在使用更新时,它会添加当前复选框行以及其他复选框值行。如果我再选中一个框,它应该再添加 1 行,依此类推。

这是我适用于更新的代码: CollDAO.java

//Insert checkbox records
public void addColl(String qId, String[] arrayColId) {
  try {
    PreparedStatement ps = con.preparedStatement("insert into colTable(qId, colId) values(?,?)");

   for(int i = 0; i < arrayColId.length; i++) {
     ps.setString(1, qId);
     ps.setString(2, arrayColId[i]);
     ps.executeUpdate();
   }
  } catch (SQLException e) {
     e.printStackTrace();
  }
}

如果我选择 2 个复选框,这就是它的样子。

rowid | qID | cID -- 正确

:101: | :121: | :9:

:100: | :121: | :13:

//Update checkbox records
public void updateColl(String qId, String[] arrayColId) {
  try {
    String sql = "update colTable set colId=?, where qId=?";
   PreparedStatement ps = con.preparedStatement(sql);

   for(int i = 0; i < colId; i++) {
     ps.setString(1, colId[i]);
     ps.setString(2, qId);
     ps.executeUpdate();
   }

  } catch (SQLException e) {
     e.printStackTrace();
  }
}

如果我选择 3 个复选框,这就是更新的内容。

rowid | qID | cID -- 错误的输出

:105: | :121: | :2:

:104: | :121: | :9:

:103: | :121: | :13:

:101: | :121: | :9:

:100: | :121: | :13:

这就是它的样子。

rowid | qID | cID -- 正确的输出

:103: | :121: | :2:

:101: | :121: | :9:

:100: | :121: | :13:

我已经为此工作了一周,有人可以帮助我吗?

谢谢

【问题讨论】:

  • 您需要检查arrayColID中的值。

标签: java arrays jdbc checkboxlist on-duplicate-key


【解决方案1】:

在您的情况下,您应该改用 Batch :

PreparedStatement ps = con.preparedStatement("your query");

for(int i = 0; i < arrayColId.length; i++) {
     ps.setString(1, qId);
     ps.setString(2, arrayColId[i]);
     ps.addBatch();    
}

ps.executeBatch();

您可以在此处了解更多信息 Reusing a PreparedStatement multiple timesStatament batching

编辑

对于您的更新,您可以使用:

connection.setAutoCommit(false);

int arrayVals = Math.min(arrayColId.length, arrayQId.length);
for (int i = 0; i < arrayVals; i++) {
    ps.setString(1, arrayColId[i]);
    ps.setString(2, arrayQId[i]);
    ps.addBatch(); //add a batch
}

ps.executeBatch();//execute your batch

connection.commit();//when you finish you should to commit your transaction

【讨论】:

  • @Gee 你可以使用批处理插入或更新或任何操作
  • 是的@Gee,你知道如何完成你的代码,或者我应该编辑我的答案吗?
  • @Gee 您是否将操作设置在connection.setAutoCommit(false);connection.commit(); 之间
猜你喜欢
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
  • 2013-04-15
  • 2016-10-26
  • 2019-02-25
  • 2016-03-13
  • 1970-01-01
  • 2016-03-13
相关资源
最近更新 更多