【问题标题】:Inserting data from a list into table将列表中的数据插入表中
【发布时间】:2016-01-15 16:15:14
【问题描述】:

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

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 中检查表没有填充任何数据。我做错了什么?

编辑:命令对象:

【问题讨论】:

  • 我没看到你在哪里 DIM fields,它的类型是什么?它是什么数组?
  • @TabAlleman 我刚刚添加了它并进行了编辑。这是一个字符串数组。
  • 在 ExecuteNonQuery 行上使用断点并查看命令对象以查看您传递的参数值。
  • 在某些时候,您可能应该执行insertTrans.Commit()
  • 开启 Option Strict fields = item.Split("__||__") 不会像您认为的那样做。在调试中检查结果(字段内容和大小)。见:i.imgur.com/CAWzL3V.jpg

标签: .net sql-server vb.net


【解决方案1】:

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

insertTrans.Commit()

最好在 Try..Catch 中执行此操作,以便您可以在需要时致电 insertTrans.Rollback()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2015-08-19
    • 2017-06-13
    相关资源
    最近更新 更多