2014-04-28 52 views
1

我正嘗試使用VB.NET讀取CSV文件,然後將數據傳遞給SQL Server表。將數據傳遞給SQL Server時的CommandText問題

我有下面的代碼,但它與失敗:

「 'System.InvalidOperationException' 類型的未處理的異常出現在system.data.dll」

「的其他信息:的ExecuteReader:CommandText中屬性尚未初始化」

它似乎對失敗這行代碼:

Dim iRowsInserted As Int32 = _ 

誰能幫我指點迷津Ø爲什麼?

下面

全碼:

Dim table As New DataTable() 

    table.Columns.Add("ZipCode") 
    table.Columns.Add("State") 
    table.Columns.Add("City") 

    Dim parser As New FileIO.TextFieldParser("c:\uploads\zipcode.csv") 

    parser.Delimiters = New String() {","} ' fields are separated by comma 
    parser.HasFieldsEnclosedInQuotes = True ' each of the values is enclosed with double quotes 
    parser.TrimWhiteSpace = True 
    parser.ReadLine() 

    Do Until parser.EndOfData = True 
     table.Rows.Add(parser.ReadFields()) 
    Loop 

    Dim strSql As String = "INSERT INTO tblZipCode (ZipCode,State,City) VALUES (@ZipCode,@State,@City)" 
    Dim SqlconnectionString As String = "server=barry-laptop\SQLEXPRESS; database=Test; integrated security=yes" 
    Using connection As New SqlClient.SqlConnection(SqlconnectionString) 

     Dim cmd As New SqlClient.SqlCommand(Sql, connection) ' create command objects and add parameters 
     With cmd.Parameters 
      .Add("@ZipCode", SqlDbType.VarChar, 15, "ZipCode") 
      .Add("@State", SqlDbType.VarChar, 20, "State") 
      .Add("@City", SqlDbType.VarChar, 30, "City") 
     End With 

     Dim adapter As New SqlClient.SqlDataAdapter() 
     adapter.InsertCommand = cmd 

     '--Update the original SQL table from the datatable 
     Dim iRowsInserted As Int32 = _ 
      adapter.Update(table) 

    End Using 

End Sub 

非常感謝,

+0

您的代碼億韓元根本不會編譯。你還沒有聲明'Sql'。也許它一定是'strSql'。 –

+0

非常感謝你 - 這就是答案 – user3580480

回答

0

昏暗CMD作爲新SqlClient.SqlCommand(STRSQL,連接)

是正確的

相關問題