我的表中有两列“res_allocation”,一个是“ResName”,另一个是“PID”,“ResName”将有一个“PID”的多个值。
是否存在基于PID更新多行“ResName”值的单个查询?
“ResName”的新值是动态的,即用户输入。我使用SQL数据库。
答案 0 :(得分:1)
这已经改编自我已经拥有的代码......可能有一两个错误,但症结将起作用(它在我的代码中有效)。理想情况下,这样的事情应该使用像Hiberante这样的ORM工具来完成。
基本上,您设置了批量更新,然后运行statement.executeBatch()来进行实际更新。返回带有结果的int []数组。您可以根据预定义常量列表检查这些常量以查看正在发生的事情。这比单独执行每个更新要快得多。此外,您可以在一个事务中组合所有更新,从而使回滚更容易。
public void updateResNames(List<ResAllocationDTO> list) {
String sql = "UPDATE res_allocation SET ResName = ? WHERE PID = ?";
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
for (ResAllocationDTO dto : list) {
statement.setString(1, dto.getResName());
statement.setString(2, dto.getPID());
statement.addBatch();
}
int[] result = statement.executeBatch();
for (int i = 0; i < result.length; i++) {
if (result[i] == PreparedStatement.EXECUTE_FAILED) {
throw new SQLException(String.format("Entry %d failed to execute in the batch insert with a return code of %d.", i, result[i]));
}
}
commit();
} catch (SQLException e) {
logger.error(LoggerCodes.DATABASE_ERROR, e);
rollback();
throw new RuntimeException(e);
} finally {
close(statement);
}
}
commit(),close()和rollback()如下所示:
public void close(PreparedStatement statement) {
try {
if (statement != null && !statement.isClosed())
statement.close();
} catch (SQLException e) {
logger.debug(LoggerCodes.TRACE, "Warning! PreparedStatement could not be closed.");
}
}
protected void commit() {
try {
if ((connection != null) && !connection.getAutoCommit()) {
connection.commit();
}
} catch (SQLException e) {
logger.debug(LoggerCodes.TRACE, "Warning! ResultSet could not be closed after commit.");
}
}
protected void rollback() {
try {
if ((connection != null) && !connection.getAutoCommit()) {
connection.rollback();
}
} catch (SQLException e) {
logger.debug(LoggerCodes.TRACE, "Warning! ResultSet could not be closed after rollback.");
}
}
我希望这会对你有所帮助!祝你好运,编码愉快!