声明登录查询

时间:2013-01-25 09:07:48

标签: vb.net parameters oledb

Function Authenticate(ByVal UserName As String, ByVal Password As String)
    Dim con As New OleDbConnection(connectionstring)

    Dim cmdstring As String
    cmdstring = "SELECT username, password  FROM tblUsers where username = @user AND password = @pass"

    con.Open()

    Dim cmd As OleDbCommand = New OleDbCommand(cmdstring, con)

    cmd.Parameters.AddWithValue("@user", OleDbType.VarChar).Value = UserName
    cmd.Parameters.AddWithValue("@pass", OleDbType.VarChar).Value = Password

    Dim sdr As OleDbDataReader = cmd.ExecuteReader()
    If (sdr.HasRows) Then
        Authenticate = True
    Else
        Authenticate = False
    End If
    sdr.Close()
    con.Close()
    con = Nothing
    Return Authenticate
End Function

任何人都可以提供帮助,不知道为什么我一打到A scalar variable '@user' needs to be declared就会收到这句话:

Dim sdr As OleDbDataReader = cmd.ExecuteReader()

4 个答案:

答案 0 :(得分:2)

您需要输入值,而不是类型,并使用如下函数:

cmd.Parameters.AddWithValue("@user", UserName)
cmd.Parameters.AddWithValue("@pass", PassWord)

这将解决您的错误。在这里您有更多信息: Documentation

答案 1 :(得分:0)

答案如下

cmdstring = "SELECT username, password  FROM tblUsers where username = ? AND password = ?"

con.Open()

Dim cmd As OleDbCommand = New OleDbCommand(cmdstring, con)

cmd.Parameters.AddWithValue("@user", UserName)
cmd.Parameters.AddWithValue("@pass", Password)

出于某种原因,?在查询中诀窍,addwithvalues还添加了值得尊重的值?在查询中,花了一段时间才找到这个,所以我想我会分享:)

答案 2 :(得分:-1)

字符串后 Dim cmdstring As String     cmdstring =“SELECT用户名,密码FROM tblUsers,其中username = @user AND password = @pass”

cmdstring cmdstring.replace(“@ user”,“'”& UserName&“'”).replace(“pPassWord”,“'”& PassWord&“'”)

将创建正确的查询

答案 3 :(得分:-2)

尝试将.ExecuteReader()更改为ExecuteNonQuery()

Dim sdr As OleDbDataReader = cmd.ExecuteNonQuery()

这是关于ExecuteReader, ExecuteNonQuery, ExecuteScalar ... When to use What?

的一个很好的解释