如果一行失败,如何继续插入

时间:2011-12-14 09:15:10

标签: sql vb.net insert

我有一个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

我需要上面的代码才能在捕获异常后继续。

由于

2 个答案:

答案 0 :(得分:3)

尝试并捕获不退出程序,它们只是控制代码的流程,以防异常发生。

当try块中发生异常时,执行将继续执行(对应的)catch块的第一行。在执行catch块之后,代码在catch之后的第一行继续,在你的情况下可以是End While,它将继续循环。
所以像这样的结构

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

应该适合你。
但是,这是一个糟糕的设计,因为它将生成并记录异常,无论问题是什么,数据是否无效,或者sql server是否已关闭,或者即使代码中存在错误(例如某些潜伏着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

答案 1 :(得分: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.)