2011-12-14 46 views
0

我有一個while循環,它從csv獲取記錄並插入到sql表中。現在csv可能包含很多行。如何在一行失敗時繼續插入

我想要的是如果一行失敗只是登錄到一個文件,並繼續下一個記錄。我正在考慮嘗試和趕上,但這將退出程序。那麼,有什麼建議?

 
while (csv.readnextline) 
'assign csv columns to objects 
try 
'insert to db 
Catch ex As Exception 
'write to log file 
End Try 

我需要上面的代碼來捕捉異常後繼續。

感謝

+0

爲什麼*捕捉*異常終止你的程序?你能提供一些代碼嗎? – Markus 2011-12-14 09:19:09

回答

0

不,它不會退出程序,具體取決於你如何/在哪裏處理異常。如果你這樣做:

Dim WrongValuedLinesList As New List(Of String) 
Dim ConversionFailedList As New List(Of String) 
Dim InsertionFailedList As New List(Of String) 
Dim NumberOfInsertedLines As integer = 0 

For Each (CurrentLine in my csv) 
    ' 1. line processing 
    Try 
    ' (process my line : split, convert, check range...) 
    If (I know the insertion will fail) Then 
     ' (Store information about that wrong line, in List, log, or do nothing) 
     WrongValuedLinesList.Add(" This line : " & CurrentLine 
               & " has wrong values because... 
     Continue For 
    End If 
    Catch ex as exception 
    ' (here handle the line conversion failed : store in list, or log, or do nothing ...) 
    ' for expl : 
     ConversionFailedList.Add(" Conversion failed for line " & CurrentLine 
             & " exception details : " & ex.message ") 
    End Try 
    ' 2. Line insertion 
    Try 
    '(insert my processed data into database) 
    NumberOfInsertedLines +=1 
    Catch ex as exception 
    ' (here handle the insertion failed exception (expl : primary key might not be unique) 
    '      : store in list, log, do nothing...) 
    ' for example : 
    InsertionFailedList.Add(" Insertion failed for line " & CurrentLine 
             & " exception details : " & ex.message ") 
    End Try 
Next 

(Here you might wanna report how things went to your user using 
    your error list.) 
3

try和catch不退出程序,他們只是控制代碼的情況下,一些特殊情況發生流動。

當try塊中發生異常時,執行繼續在(對應的)catch塊的第一行。在執行catch塊之後,代碼會在catch之後的第一行繼續執行,在您的情況下,該代碼可能是End While,它將繼續循環。
所以這樣

While dr.Read 
    Try 
    InsertRowIntoDataBase() 
    Catch ex As Exception 
    LogErrorToFile(ex) 
    End Try 
End While 

的建設應該爲你工作。
但是,這是一個糟糕的設計,因爲它會生成並記錄一個異常,無論問題是什麼,數據是無效的,還是sql服務器關閉,或者即使代碼有錯誤例如潛伏的NullReferenceException)。您應該限制對特定情況的例外處理,例如與數據庫中的問題,如:

While dr.Read 
    Try 
    InsertRowIntoDataBase() 
    Catch ex As SqlClient.SqlException 
    LogDataBaseErrorToFile(ex) 
    End Try 
End While 

此外,如果有一些已知的數據可能存在的問題(例如,在CSV一個字符串,其中一個整數預期)最好是剛剛檢查,而不是使用一個例外機制,沿着這些線:

While dr.Read 
    Try 
    If Not IsRowValid() Then 
     LogInvalidDataToFile() 
     Continue While 
    End If 
    InsertRowIntoDataBase() 
    Catch ex As SqlClient.SqlException 
    LogDataBaseErrorToFile() 
    Catch ex As Exception 
    LogGenericErrorToFile() 
    End Try 
End While 
相關問題