导致VB.NET代码无法正常运行的异常

时间:2011-10-21 11:46:45

标签: sql-server vb.net

当我运行下面的VB.NET代码来验证用户时,我得到一个异常。例外说“变量用户附近的语法不正确”

谁能告诉我哪里出错?

      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    If TextBox1.Text.Trim().Length = 0 Or TextBox2.Text.Trim().Length = 0 Then
        MsgBox("Enter a user id and password")
        Return 'Terminate this method
    End If

    Dim myconnection As SqlConnection
    Dim mycommand As SqlCommand
    Dim dr As SqlDataReader
    Dim userid = TextBox1.Text
    Dim password = TextBox2.Text

    Try
        myconnection = New SqlConnection("server=PARTH- PC\SQLEXPRESS;uid=sa;pwd=parth;database=fcrit")

        myconnection.Open()
        mycommand = New SqlCommand("select * from user where [user id]=@userid and [password]=@password", myconnection)
        mycommand.Parameters.Add("@userid", SqlDbType.VarChar, 30).Value = userid
        mycommand.Parameters.Add("@password", SqlDbType.VarChar, 30).Value = password

        'mycommand = New SqlCommand("select * from user where user id='" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", myconnection)
        dr = mycommand.ExecuteReader()

        If (dr IsNot Nothing) Then
            If (dr.Read()) Then
                MsgBox("User is authenticated")
                Form2.Show()
            Else
                MsgBox("Please enter correct username and password")
            End If
        End If
        myconnection.Close()
    Catch ex As Exception
        Throw

    Finally
    End Try
  End Sub

2 个答案:

答案 0 :(得分:3)

尝试将SQL更改为 -

"select * from [user] where [user id]=@userid and [password]=@password"

根据this page'用户'是保留字

答案 1 :(得分:2)

User是SQL Server中的保留字。

在表名周围加上括号:

mycommand = New SqlCommand("select * from [user] where [user id]=@userid and [password]=@password", myconnection)