代码之家  ›  专栏  ›  技术社区  ›  Boneyt

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

  •  -1
  • Boneyt  · 技术社区  · 11 年前

    嗨,我在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 回复  |  直到 11 年前
        1
  •  2
  •   Steve    11 年前

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

    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
    
        2
  •  1
  •   stakx - no longer contributing Saravana Kumar    11 年前

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

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

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