将列表中的数据插入表中

时间:2016-01-15 16:15:15

标签: .net sql-server vb.net

我正在尝试遍历列表并插入数据库。

Dim fields() As String
Using cnn As SqlConnection = New SqlConnection(conn)
  cnn.Open()
  Using insertTrans As SqlTransaction = cnn.BeginTransaction
    Using cmd As SqlCommand = cnn.CreateCommand()
      'create command
      cmd.CommandText = "INSERT INTO [matrixtest].[dbo].[SM_Fatca_GinList] " _
                      & "(gincode, ginname, country) VALUES (@gin, @name, @country)"
      Dim gin As SqlParameter = New SqlParameter("@gin", SqlDbType.VarChar)
      Dim companyName As SqlParameter = New SqlParameter("@name", SqlDbType.VarChar)
      Dim country As SqlParameter = New SqlParameter("@country", SqlDbType.VarChar)
      cmd.Parameters.Add(gin)
      cmd.Parameters.Add(companyName)
      cmd.Parameters.Add(country)
      'skip 1st row
      Dim firstRow As Boolean = True
      For Each item As String In lines
        If Not firstRow Then
          fields = item.Split("__||__")
          If Not String.IsNullOrEmpty(fields(0)) Then
            If Not fields(0).Length = 0 Then
              'set parameters
              gin.Value = fields(0)
              companyName.Value = fields(1)
              country.Value = fields(2)
              cmd.Transaction = insertTrans
              cmd.ExecuteNonQuery()
            End If
          End If
        End If
        firstRow = False
      Next
    End Using
  End Using
End Using

但是我的代码只是继续运行并且在SSMS中检查表中没有填充任何数据。我做错了什么?

编辑:命令对象:

enter image description here

1 个答案:

答案 0 :(得分:2)

您没有提交交易,因此您必须添加:

insertTrans.Commit()

最好在Try..Catch中执行此操作,以便在需要时拨打insertTrans.Rollback()