这取决于插入行的方式。如果要将它们插入到已由关闭自动提交的连接上的单个事务中
connection.setAutoCommit(false)
在使用完成insert查询之后,您将提交连接
connection.commit()
你明确地打电话给
connection.rollback()
在catch块中,则整个事务将回滚。否则,你就依赖于你无法控制的环境因素。
另请参见:
更新:
这是你的代码重写。注意,连接和语句应该在
try
尝试
finally
. 这是为了防止异常情况下的资源泄漏。
String sql = "insert into job_input values (?, ?)";
Connection connection = null;
PreparedStatement statement = null;
try {
connection = database.getConnection();
connection.setAutoCommit(false);
statement = connection.prepareStatement(sql);
for (List row : data) {
statement.setInt(1, Integer.parseInt(row.get(0).toString()));
statement.setInt(2, Integer.parseInt(row.get(1).toString()));
statement.addBatch();
}
statement.executeBatch();
connection.commit();
return true;
} catch (SQLException e) {
if (connection != null) try { connection.rollback(); } catch (SQLException logOrIgnore) {}
e.printStackTrace();
return false;
} finally {
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
顺便说一句,我不喜欢退货
boolean
在这里。我只是想办法
void
catch
throw e
把呼叫码放在
try-catch
.