Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 异常后保留jdbc批处理语句_Java_Postgresql - Fatal编程技术网

Java 异常后保留jdbc批处理语句

Java 异常后保留jdbc批处理语句,java,postgresql,Java,Postgresql,我正在将java中的数据插入postgresql数据库。我正在使用jdbc postgresql驱动程序建立连接。我正在创建一批语句并一次性发送到insert。但若连接丢失,那个么java会尝试使用连接池再次连接数据库。我试图再次执行批处理,但未插入任何记录 PreparedStatement pstmt = connection.prepareStatement(INSERT_RECORD_TABLE_SQL); while (iterator.hasNext()) { pstmt.set

我正在将java中的数据插入postgresql数据库。我正在使用jdbc postgresql驱动程序建立连接。我正在创建一批语句并一次性发送到insert。但若连接丢失,那个么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)

抓住一般例外是件坏事

睡一分钟或任何其他“人类”时间价值观都是一件坏事

在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;
}

你需要交易吗?也就是说,如果您回滚到数据库启动前的状态时发生错误,或者可以重试吗?

我使用的是BatchUpdateException,但我在问题中提到它是错误的。我将线程置于睡眠状态,以便它再次与数据库重新连接。如果我不再执行批处理,那么我将丢失数据。如果我错了,请更正。preparedStatement.executeBatch()将作为一个事务而不是两个或多个语句更新整个批处理。因此,我想再次尝试插入同一批。这取决于您使用的java版本。Java 2 SDK标准版1.3版中可能的实现和返回值已修改,以适应在抛出BatchUpdateException对象后继续处理批更新中的命令的选项