标准表达式中的数据类型不匹配VB.NET中的错误

时间:2015-02-15 11:02:07

标签: vb.net ms-access-2013

您好我在尝试以下代码时在VB中遇到上述错误,我在表单上有3个文本框,用户输入股票代码后我希望表单输入匹配的产品组和相关的产品描述文本框。我使用的代码如下

Private Sub txt_productcode_Leave(sender As Object, e As EventArgs) Handles txt_productcode.Leave
    Dim dt As New DataTable
    Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:database
    Dim SqlString As String = "select [product group],[product description] from [stock] where [stock code] = " & txt_productcode.Text & ""
    Using conn As New OleDbConnection(connstring)
        Using command As New OleDbCommand(SqlString, conn)
            Using adapter As New OleDbDataAdapter(command)
                conn.Open()
                adapter.Fill(dt)
                conn.Close()
            End Using
            Dim MyDataRow As DataRow = dt.Rows(0)
            Dim x As Integer
            x = dt.Rows.Count
            For y = 0 To x - 1
                If y < x Then
                    MyDataRow = dt.Rows(y)
                    txt_productgroup.Text = MyDataRow("product group")
                    txt_productdescription = MyDataRow("product description")

                End If
            Next
        End Using
    End Using
End Sub

每当我尝试运行此表单崩溃时,我收到上面的错误消息,代码中突出显示以下行

adapter.Fill(dt)

任何人都可以解释为什么这不起作用?感谢

2 个答案:

答案 0 :(得分:2)

首先要做的是在构建命令文本并使用参数时删除字符串连接,然后为描述设置TextBox而不是text属性。删除了一些无用的代码

Private Sub txt_productcode_Leave(sender As Object, e As EventArgs) Handles txt_productcode.Leave
    Dim dt As New DataTable
    Dim connstring As String = "...."
    Dim SqlString As String = "select [product group],[product description] " & _
       "from [stock] where [stock code] = @stock"
    Using conn As New OleDbConnection(connstring)
        Using command As New OleDbCommand(SqlString, conn)
            Using adapter As New OleDbDataAdapter(command)
                conn.Open()
                command.Parameters.AddWithValue("@stock", txt_productcode.Text)
                adapter.Fill(dt)
            End Using
            For y = 0 To dt.Rows.Count - 1
                Dim MyDataRow = dt.Rows(y)
                txt_productgroup.Text = MyDataRow("product group").ToString()
                txt_productdescription.Text = MyDataRow("product description").ToString()

            Next
        End Using
    End Using
End Sub

答案 1 :(得分:1)

嗯,您的SQL语句可能包含错误。也许您在WHERE条件中缺少引号字符:

"… WHERE [stock code] = '" + ... + "'"
'                       ^           ^

顺便说一下。由于使用简单的字符串连接而不是使用参数化查询来构建SQL命令,因此您的代码容易受到SQL注入攻击。