我将java中的数据插入到postgresql数据库中。我正在使用jdbc postgresql驱动程序进行连接。我正在创建一批语句并一次性发送插入。但是如果连接丢失,那么java会尝试使用连接池再次连接数据库。我试图再次执行批处理但没有插入记录。
PreparedStatement pstmt = connection.prepareStatement(INSERT_RECORD_TABLE_SQL);
while (iterator.hasNext()) {
pstmt.setLong(1, toLong(fields[0]));
pstmt.setLong(2, toLong(fields[1]));
....
pstmt.addBatch();
}
try{
pstmt.executeBatch();
} catch (Exception e) {
Thread.sleep(60000);
pstmt.executeBatch();
}
我的问题是,如果发生异常,我可以保留一批可以执行的语句吗?
谢谢,
Saurabh Gupta
答案 0 :(得分:2)
抓住一般的例外是一件坏事。
睡一分钟或任何其他“人”时间值是一件坏事。
在catch块中重新执行相同的代码是一件坏事,就像没有发生任何事情一样,但是你在那里处理异常!你应该在catch块中捕获新的可能异常。
最好:
try
{
int[] updateCounts = pstmt.executeBatch();
}
catch (BatchUpdateException be)
{
// if one of the commands sent to the database fails to execute properly
// or attempts to return a result set
handleException(be);
return;
}
catch (SQLException se)
{
//if a database access error occurs, this method is called on a closed Statement
//or the driver does not support batch statements
handleException(se);
return;
}
您需要交易吗?也就是说,如果发生错误,你应该回滚到db在你开始之前的状态,还是可以重试?