【问题标题】:Using PreparedStatements - update using multiple parameters (unknown number)使用 PreparedStatements - 使用多个参数更新(未知数)
【发布时间】:2015-03-29 07:33:01
【问题描述】:

我了解最佳做法是拥有固定数量的参数,然后使用preparedStatement.setParam(xxx) 定义它们。

如果我有一个学生 ID 列表,我想为每个学生数据行更新一列:

update student set student_grade=FAIL where student_id in (?) 其中? 将是我的列表对象中的学生ID 列表。这样做的最佳方法是什么?

【问题讨论】:

  • 循环遍历你的学生,在每个学生的更新语句中插入一个?
  • 使用 Apache commons' StringUtils 类 - StringUtils.repeat("?", ",", ids.size());

标签: java mysql sql jdbc prepared-statement


【解决方案1】:

/* 我宁愿使用单独的更新并循环它们而不是使用 IN 运算符,类似于 GriffeyDog 的建议。建议将批量更新拆分为 1000 或更少。*/

/* 假设 al 是包含 student_ids 列表的数组列表,并且假设 student_ids 数据类型是 int */

String updateTableSQL = "update student set student_grade='FAIL' where student_id = (?) ";              
PreparedStatement preparedStatement = dbConnection.prepareStatement(updateTableSQL);
for (int i=0;i<al.size();i++){
preparedStatement.setInt(1,al.get(i) );
preparedStatement.addBatch();

}
preparedStatement.executeBatch();

dbConnection.commit();

【讨论】:

  • 为什么? IN 算子的速度会更快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
  • 2018-09-06
  • 2011-11-22
  • 2019-12-16
  • 2013-02-17
  • 1970-01-01
  • 2021-11-20
相关资源
最近更新 更多