条件表达式中的数据类型不匹配。 MS Access VB

时间:2013-10-01 14:22:56

标签: vb.net visual-studio-2010 visual-studio ms-access ms-access-2010

'确定按钮

Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
    Dim con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\Jill\Desktop\saddbase\Sadsystem\Sadsystem\bin\Debug\tenant.mdb")
    Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM info WHERE TN_ID = '" & UsernameTextBox.Text & "' AND Password = '" & PasswordTextBox.Text & "' ", con)
    con.Open()
    Dim sdr As OleDbDataReader = cmd.ExecuteReader()
    ' If the record can be queried, Pass verification and open another form.  
    If (sdr.Read() = True) Then
        MessageBox.Show("The user is valid!")

        Me.Hide()
    Else
        MessageBox.Show("Invalid Tenant ID or password!")


End If

当我运行程序时,cmd.ExecuteReader()中出现错误。 条件表达式中的数据类型不匹配请帮助解决此错误的方法。

2 个答案:

答案 0 :(得分:2)

在您的查询中,您为TN_ID和密码字段传递两个字符串 可能TN_ID是一个数字字段,你不需要在它周围加上引号,我发现你传递UserName文本框的值真的很奇怪。

说,我希望检查一下你的查询,因为你有没有看到潜在的问题:

首先,PASSWORD是一个保留的关键字,因此你需要在它周围使用Square Brackets 其次,不要使用字符串连接来构建sql命令,而是使用像这样的参数化查询

Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click

    Dim commandText = "SELECT * FROM info WHERE TN_ID = ? AND [Password] = ?"
    Using con = New OleDbConnection(......))
    Using cmd = New OleDbCommand(commandText,con))
       con.Open()

       ' If the TN_ID is really a numeric field then you need '
       ' to conver the first parameter to a number '
       ' cmd.Parameters.AddWithValue("@p1", Convert.ToInt32(UsernameTextBox.Text))'

       cmd.Parameters.AddWithValue("@p1", UsernameTextBox.Text)
       cmd.Parameters.AddWithValue("@p2", PasswordTextBox.Text)
       Using sdr As OleDbDataReader = cmd.ExecuteReader())
        .....
       End Using
    End Using
    End Using    
End Sub

作为旁注,与您的问题无关,请注意不要在数据库中以纯文本形式存储密码。有一些技术可以将密码文本HASH并将结果存储在数据库中。这样,只需查看数据库文件就无法获取密码。 See the details in this question

答案 1 :(得分:0)

Private Sub SumOfIR()

    Try
        Dim con As New System.Data.OleDb.OleDbConnection(ConnectionString)
        Dim com As New System.Data.OleDb.OleDbCommand

        con.Open()
        com.Connection = con
        com.CommandText = "Select Sum(IR) from Spectrum where StdNu='" + TxtNuTeif.Text + "'"
        com.Parameters.Clear()
        Dim SumIR As OleDbDataReader = com.ExecuteScalar
        LblIRTeif.Text = com.ExecuteScalar("SumIR").ToString
        con.Close()
        com.Dispose()

    Catch ex As Exception
        BehComponents.MessageBoxFarsi.Show(ex.ToString, "", BehComponents.MessageBoxFarsiButtons.OK, MessageBoxIcon.Warning)

    End Try

End Sub