【问题标题】:Type mismatch in criteria expression条件表达式中的类型不匹配
【发布时间】:2015-02-16 21:22:37
【问题描述】:

我是 Visual Basic 的新手。我想删除基于电话号码的记录。程序将要求用户输入他的号码,并在将电话号码与数据库匹配后删除记录。我试过这样做,但它给了我一个错误“标准表达式中的类型不匹配”。 我正在使用 ms access 2007 并且我已将 phone 列的数据类型指定为 Number 。这是我的 vb 代码。请帮我 。这一定是我犯的愚蠢错误之一。在插入数据模块中,我已将数据类型指定为 Long,在此之前我已将其指定为 Integer,但同样的错误仍然存​​在。

Imports System.Data.OleDb
Public Class Form5
    Public Connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\AMEN\Documents\Railway.accdb"
    Public Conn As New OleDbConnection

    Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Conn.ConnectionString = Connstring
        If Conn.State = ConnectionState.Closed Then
            Conn.Open()
        End If

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim okToDelete As MsgBoxResult = MsgBox("Are you sure you want to cancel your ticket?", MsgBoxStyle.YesNo)

        If okToDelete = MsgBoxResult.Yes Then
            Dim str As String
            str = "Delete from Table2 Where Phone = '" & TextBox1.Text & "'"
            Dim cmd As OleDbCommand = New OleDbCommand(str, Conn)
            Try
                cmd.ExecuteNonQuery()
                cmd.Dispose()
                Conn.Close()

                MsgBox("Your Ticket Cancelled Sucessfully ! ")
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        ElseIf okToDelete = MsgBoxResult.No Then
        End If

    End Sub
End Class

【问题讨论】:

  • 如果 phone 是一个数字字段(错误!!!)那么你不需要在你的文本框值周围加上引号

标签: vb.net visual-studio-2010 type-mismatch


【解决方案1】:

电话号码应存储为字符串而不是数字。 但是,如果您的电话字段是数字,那么您的查询是错误的。
在这种情况下,您不需要在 TextBox1.Text 周围加上引号。这会将您的输入视为字符串,并且该字符串不能用于在数字字段中进行搜索。

最好的方法是使用参数化查询,您可以在其中指定传递的参数的数据类型
(我假设您已在 Access 中创建字段电话作为长号码)

If okToDelete = MsgBoxResult.Yes Then

    ' Check if your user types really a number.
    Dim number As Integer
    if Not Int32.TryParse(TextBox1.Text, number) Then
        MessageBox.Show("Not a valid number!")
        return
    End If
    Dim str As String
    str = "Delete from Table2 Where Phone = @phone"
    Dim cmd As OleDbCommand = New OleDbCommand(str, Conn)
    Try
        cmd.Parameters.Add("@phone", OleDbType.Integer).Value = number
        cmd.ExecuteNonQuery()
        ....

【讨论】:

  • 非常感谢您的回答!!!我将 phone 的数据类型更改为 String 并且它起作用了。非常感谢!
  • 高德来帮忙。作为该网站的新用户,我建议您阅读How does accepting an answer work?,然后,如果您发现我的或在您的其他问题中收到的其他答案有用,请考虑接受它们
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多