【问题标题】:How to fix incorrect syntax near '?'如何修复“?”附近的错误语法
【发布时间】:2019-01-18 20:10:42
【问题描述】:

当我执行此代码时,我在 SQL 命令中遇到错误

'?' 附近的语法不正确

这是我的代码:

Dim command As New SqlCommand("SELECT [username], [password] FROM [stud_table] WHERE [username] = ?", connection)
command.Parameters.AddWithValue("username", Me.UsernameTextBox.Text)

Try
    connection.Open()

    Dim adapter As New SqlDataAdapter(command)

    Dim rec As SqlDataReader = command.ExecuteScalar()

    If rec.HasRows Then
        rec.Read()

        If Me.PasswordTextBox.Text.ToLower = rec.Item("password").ToString Then
            MsgBox("Login successful")
            Me.Hide()
            user_profile.Show()
        Else
            MsgBox("Login unsuccessful, Incorrect Password", MsgBoxStyle.OkOnly, "Invalid")
        End If
    Else
        MsgBox("Login unsuccessful, Invalid UserName", MsgBoxStyle.OkOnly, "Invalid")
    End If
    rec.Close()
Catch ex As OleDb.OleDbException
    MsgBox("Login unsuccessful,no connection", MsgBoxStyle.OkOnly, "Invalid")
Catch ex As Exception
    MessageBox.Show(ex.Message)
Finally
    connection.Close()
End Try

【问题讨论】:

  • Sql Server 不使用 ?作为参数的占位符。它使用@后跟代表参数名称的字符串
  • 不要将密码存储为纯文本。
  • 您正在使用 SqlCommand 和 SqlDataAdapter,但您正在捕获 OleDbException。你用的是什么数据库???

标签: sql-server vb.net


【解决方案1】:

在查询中使用参数名称:

Dim command As New SqlCommand("SELECT [username],[password] FROM [stud_table] WHERE [username] = @username", connection)
        command.Parameters.AddWithValue("@username", SqlDbType.NVarChar) = Me.UsernameTextBox.Text

【讨论】:

  • 请不要建议使用 AddWithValue。有很多文章解释它存在问题,例如AddWithValue is EvilAddWithValue is evil! 不过语法修正还是不错的。
  • @AndrewMorton 感谢您的注意,我已经使用首选重载编辑了语法更正。
  • 非常感谢,它帮助解决了语法错误。
  • @aartitirthapramodkumar 如果解决了您的问题,请将答案标记为已接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-14
  • 2019-09-11
相关资源
最近更新 更多