0

我有以下代码,

    OleDbCommand cmd = new OleDbCommand("SELECT * FROM Users WHERE username = ? AND password = ?",conn);

    OleDbParameter p1 = new OleDbParameter();
    OleDbParameter p2 = new OleDbParameter();
    cmd.Parameters.Add(p1);
    cmd.Parameters.Add(p2);
    p1.Value = usernametb.Text;
    p2.Value = passwordtb.Text;

    conn.Open();
    OleDbDataReader read = cmd.ExecuteReader();

        if (read.Read() == true)
        {
            conn.Close();
            MessageBox.Show("Successfully logged in!");
        }
        else
        {
            conn.Close();
            MessageBox.Show("Login failed");
        }

如果用户有密码,此代码对我有用,但如果用户没有密码,那么它会失败,我不知道为什么。

我哪里错了?

4

2 回答 2

1

这是因为在 SQL 标准中null = null返回null而不是true.

您的查询应该是

SELECT * FROM Users WHERE username = ? AND (password is null or password = ?)

一个更好的查询是检查当密码是null用户必须输入一个空密码时,它会是这样的:

SELECT * FROM Users WHERE username = ? AND 
    ? = case when password is null then '' else password end
于 2013-05-22T13:41:46.987 回答
0

下面的工作吗?

SELECT * FROM Users WHERE username = ? AND 
                          (password IS NULL OR password = ?)
于 2013-05-22T13:41:39.847 回答