SqlDataAdapter 不使用 SQL Where 子句填充数据表



尝试使用SqlDataAdapterWHERE子句填充数据表,但未返回任何内容。SQL 命令本身从 SSMS 返回数据,仅删除代码中的WHERE子句会按预期填充数据表。

Dim adapter As New SqlDataAdapter
Dim datatable As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
adapter = New SqlDataAdapter("SELECT * FROM [MyProjectDtbl] WHERE zipcode = 22021", cnn)
adapter.Fill(datatable)
adapter.Dispose()
End Using

通过挖掘选择命令EventSink,我发现:

无法将类型为"System.Data.SqlClient.SqlInternalConnectionTds"的对象转换为类型"System.Data.SqlClient.SqlInternalConnectionSmi">

尝试使用参数。

Private Sub OPCode()
Dim dt As New DataTable
Using cnn As New SqlConnection(connectionString),
cmd As New SqlCommand("SELECT * FROM [MyProjectDtbl] WHERE zipcode = @zip", cnn)
cmd.Parameters.Add("@zip", SqlDbType.Int).Value = 22021
cnn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Debug.Print(dt.Rows.Count.ToString)
End Sub

最新更新