我有以下代码将数据从CSV文件导入到sql表中。当我运行代码时,不会显示错误。但是没有任何内容插入到SQL表中。
Dim folder = "C:\Users\Administrator\Desktop\SKEDULERING\Data\"
Dim CnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
Dim dt As New DataTable
Using Adp As New OleDbDataAdapter("select * from [labanal2.csv]", CnStr)
Adp.Fill(dt)
End Using
Dim strsql As String = "insert into ontledings (PLAASNO,PLAASNAAM,BLOKNO,AREA,NAME3,KULTIVAR,WINGKLAS,ANALISEDATUM,SUIKER,pH,SUUR) values (@PLAASNO,@PLAASNAAM,@BLOKNO,@AREA,@NAME3,@KULTIVAR,@WINGKLAS,@ANALISEDATUM,@SUIKER,@pH,@SUUR)"
Dim SqlconnectionString As String = "Data Source=GIDEON-E-LAPTOP\SQLEXPRESS2014;Initial Catalog=SkeduleringDatabasis;Integrated Security=True"
Using connection As New SqlClient.SqlConnection(SqlconnectionString)
Dim cmd As New SqlClient.SqlCommand(strsql, connection)
With cmd.Parameters
.Add("@PLAASNO", SqlDbType.VarChar, 50, "PLAASNO")
.Add("@PLAASNAAM", SqlDbType.VarChar, 50, "PLAASNAAM")
.Add("@BLOKNO", SqlDbType.VarChar, 50, "BLOKNO")
.Add("@AREA", SqlDbType.VarChar, 50, "AREA")
.Add("@ANALISEDATUM", SqlDbType.Date, 50, "ANALISEDATUM")
.Add("@NAME3", SqlDbType.VarChar, 50, "NAME3")
.Add("@KULTIVAR", SqlDbType.VarChar, 50, "KULTIVAR")
.Add("@WINGKLAS", SqlDbType.VarChar, 50, "WINGKLAS")
.Add("@SUIKER", SqlDbType.Decimal, 50, "SUIKER")
.Add("@pH", SqlDbType.Decimal, 50, "pH")
.Add("@SUUR", SqlDbType.Decimal, 50, "SUUR")
End With
Dim adapter As New SqlClient.SqlDataAdapter()
adapter.InsertCommand = cmd
Dim iRowsInserted As Int32 = adapter.Update(dt)
MsgBox("Klaar OLEB")
End Using
我错过了什么?
答案 0 :(得分:1)
问题是由DataTable中的每一行都有RowState = DataRowState.Unchanged引起的。这意味着当您调用Update时,将忽略每一行。
这是Update方法预期的正常行为,只考虑Insert,Update或Delete命令中的“添加,更改或删除”状态的行。
您可以在调用update
之前添加此循环For Each row As DataRow In dt.Rows
row.SetAdded()
Next
或者,如下面Plutonix所述,更改将属性AcceptChangesDuringFill
设置为False的Fill方法的行为
Using Adp As New OleDbDataAdapter("select * from [labanal2.csv]", CnStr)
Adp.AcceptChangesDuringFill = False
Adp.Fill(dt)
End Using
这将使RowState属性的DataRowState.Added标志处于活动状态。