2012-02-10 42 views
0

我將java中的數據插入到postgresql數據庫中。我正在使用jdbc postgresql驅動程序進行連接。我創建了一批語句併發送一次插入。但是如果連接丟失,那麼java會嘗試使用連接池再次連接數據庫。我試圖再次執行批處理,但沒有插入記錄。在異常後保留jdbc批處理語句

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古普塔

回答

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

你需要一個交易?也就是說,如果發生錯誤時應回滾到啓動之前數據庫的狀態,或者可以重試?

+0

我正在使用BatchUpdateException,但我提到它有問題。我把線程放在睡眠中,以便它再次與數據庫重新連接。如果我不再執行批處理,那麼我將丟失數據。請糾正我如果我錯了,preparedStatement.executeBatch()會將整個批次更新爲一個事務而不是兩個或更多語句。所以我想再次嘗試插入相同的批次。 – Saurabh 2012-02-10 09:27:11

+0

它取決於您正在使用的Java版本。 _「在Java 2 SDK Standard Edition版本1.3中修改了可能的實現和返回值,以適應在拋出BatchUpdateException對象後繼續在批處理更新中處理命令的選項。」_ – vulkanino 2012-02-10 09:34:12