首页 > 解决方案 > 查询表达式 'Kad Matrik='DDWC2017/060550 中的语法错误(缺少运算符)

问题描述

查询表达式 'Kad Matrik='DDWC2017/060550 中的语法错误(缺少运算符)这是唯一的问题,然后我不知道如何解决此编码

   Dim strName = MatrikTextBox.Text

        With objCon
            .Close()
            If .State = ConnectionState.Closed Then
                .ConnectionString = strConnection
                .Open()
            Else
                MessageBox.Show("Please Insert the correct Kad Matrik", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If

        End With

        ds.Clear()
        strSQL = "Select * from DaftarMasukPelajar where Kad Matrik='" & MatrikTextBox.Text
        da = New OleDbDataAdapter(strSQL, objCon)
        da.Fill(ds, "DaftarMasukPelajar")

        If ds.Tables("DaftarMasukPelajar").Rows.Count <> 0 Then
            MaximizeBox = True
            MinimizeBox = True
            MsgBox("Hello! " + strName + vbNewLine +
                   "Log in successful", MsgBoxStyle.OkOnly,
                   "Welcome " + strName)
            Form4.ShowDialog()
            If Form4.Visible Then
                Me.Hide()
            End If

标签: vb.net

解决方案


    With objCon
        .Close()
        If .State = ConnectionState.Closed Then
            .ConnectionString = strConnection
            .Open()
        Else
            MessageBox.Show("Please Insert the correct Kad Matrik", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End With

这第一段代码没有意义。您关闭连接,然后检查它是否已关闭并打开它。当然它是关闭的,所以 Else 永远不会运行。无论如何,正确的 Kad Matrik 与关闭连接有什么关系?

        Form4.ShowDialog()
        If Form4.Visible Then
            Me.Hide()
        End If

当前面的行显示时,为什么要检查 Form4 是否可见?

要验证用户,您不需要数据集和数据适配器,只需一个命令和一个连接。

将数据库代码与用户界面代码分开是一个好主意。Using...End Using即使出现错误,这些块也可确保您的数据库对象已关闭和处置。将这些对象保持在过程的本地,直到最后一分钟才打开连接,就在 .Execute... 之前

不要检索超出您需要的数据。当您只需要知道记录是否存在时,不要选择 *。

Private strConnection As String = "Your connection string"

Private Function ValidateUser(Matrik As String) As Boolean
    Dim ReturnValue As Integer
    Using cn As New OleDbConnection(strConnection)
        Using cmd As New OleDbCommand("SELECT COUNT(*) FROM DaftarMasukPelajar WHERE [Kad Matrik] = @KadMatrik;", cn)
            cmd.Parameters.Add("@KadMatrik", OleDbType.VarChar).Value = Matrik
            cn.Open()
            ReturnValue = CInt(cmd.ExecuteScalar)
        End Using
    End Using
    If ReturnValue = 1 Then
        Return True
    Else
        Return False
    End If
End Function

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    If ValidateUser(MatrikTextBox.Text) Then
        MaximizeBox = True
        MinimizeBox = True
        MsgBox("Hello! " & MatrikTextBox.Text & vbNewLine &
               "Log in successful", MsgBoxStyle.OkOnly,
               "Welcome " & MatrikTextBox.Text)
        Form4.ShowDialog()
        Me.Hide()
    Else
        MessageBox.Show("Sorry, invalid login")
    End If
End Sub

推荐阅读