java - 修改: How to update multiple rows in java jdbc on duplicate value

标签 java arrays jdbc checkboxlist on-duplicate-key

我有一个带有多个复选框的 .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:

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

谢谢

最佳答案

在您的情况下,您应该使用 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

关于java - 修改: How to update multiple rows in java jdbc on duplicate value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42488052/

相关文章:

mysql - 我不断收到 'could not get jdbc connection nested exception'

java - Android 中是否有 Raster.getSample(int, int, int) 的等效项?

java - 在 Arraylist 中搜索时遇到问题

java - 在本地运行,但不在服务器上运行,因为 "Data source name not found and no default driver specified"

javascript - 通过 POST 将 javascript 数组传递给 PHP 不起作用

c - 为什么 C 输出内存位置/指针而不是数组的值?

java - 无法检索我希望使用存储过程选择的值

java - 如何在java中安排每日任务?

java - JTextArea 在应该更新的时候没有更新

arrays - 返回一个映射并将结果存储在不同的变量中