我在这方面遇到了一些麻烦。
我试图列出有关在executeUpdate()期间失败的查询的一些数据,并且我读到可以捕获BatchUpdateException,然后获取updateCount,它告诉您哪些查询有效,哪些无效,但是当查询因以下原因失败时错误的数据转换,它会启动 SQLException,并且我无法捕获整个批处理执行错误。
用于进行查询的数据是从 XML 中获取的,无需任何类型的验证。
这是代码:
try {
pSt_insertCabecera.executeBatch();
}
catch (BatchUpdateException buex){
int[] updateCounts = buex.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i++) {
if (updateCounts[i] == Statement.EXECUTE_FAILED) {
logger.error(nombreClase + "[ESB_P]: Ha fallado la inserción de la cabecera de pedidos: " + cabecerasAInsertar.get(i).toString());
throw new SQLException();
}
}
}
除了 if 之外抛出的 SQLException 是因为稍后在代码中我捕获它以执行回滚。
StackTrace 如下所示:
com.microsoft.sqlserver.jdbc.SQLServerException: Error al convertir una cadena de caracteres en fecha y/u hora.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatementBatch(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtBatchExecCmd.doExecute(Unknown Source)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeBatch(Unknown Source)
我正在使用 SQL Server 2012。
如果您需要更多代码或信息,请询问。
非常感谢大家。
我能够重现您的问题。对于名为 [Clients] 的表,其datetime
名为 [DOB] 的列代码
String[] datesToApply = new String[]
{
"1978-12-31",
"junk",
"1981-11-11"
};
String sql =
"UPDATE Clients SET DOB=? WHERE ID=1";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
for (String dt : datesToApply) {
ps.setString(1, dt);
ps.addBatch();
}
int[] updateCounts = null;
try {
updateCounts = ps.executeBatch();
} catch (BatchUpdateException bue) {
System.out.println("executeBatch threw BatchUpdateException: " + bue.getMessage());
updateCounts = bue.getUpdateCounts();
} catch (SQLException se) {
System.out.println("executeBatch threw SQLException: " + se.getMessage());
}
if (updateCounts != null) {
for (int uc : updateCounts) {
System.out.println(uc);
}
}
if (!conn.getAutoCommit()) {
conn.commit();
}
抛出一个SQLException
如果 AutoCommit 已关闭,但它会抛出BatchUpdateException
如果自动提交已打开。检查返回的数组.getUpdateCounts()
向我们显示批次中第一次失败发生的点
executeBatch threw BatchUpdateException: Conversion failed when converting date and/or time from character string.
1
-3
-3
但它也表明 SQL Server 在第一次失败后就“放弃”了。似乎没有选项可以告诉 SQL Server 继续处理该批处理的其余部分(例如continueBatchOnError
对于 MySQL 连接器/J)。
此外,由于 AutoCommit 处于“开启”状态,因此该点的更新已提交,因此无法选择回滚这些更改en masse。如果您希望批处理“全有或全无”,您必须编写一些代码来返回并反转在第一次失败之前成功应用的更改。
(当然,另一个选择是验证数据before尝试将其放入您的数据库中。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)