2016-01-15 118 views
1

我想遍歷列表並插入到數據庫中。從列表中插入數據到表

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中檢查表沒有被填充任何數據。我究竟做錯了什麼?

編輯:Command對象:

enter image description here

+0

我沒有看到你的DIM'fields',它的類型是什麼?它是一個什麼樣的陣列? –

+0

@TabAlleman我剛剛添加了一個編輯。這是一個字符串數組。 –

+0

在ExecuteNonQuery行上使用斷點,並查看命令對象以查看傳遞的參數值。 –

回答

2

您還沒有提交你的事務,所以你必須補充:

insertTrans.Commit() 

最好做它在try..catch所以如果需要的話,你可以撥打insertTrans.Rollback()