OleDb参数,空值

时间:2013-05-22 13:37:09

标签: c# .net oledb

我有以下代码,

    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");
        }

如果用户有密码,此代码适用于我,但如果用户没有密码,则会失败并且我不知道原因。

我哪里错了?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

以下是否有效?

SELECT * FROM Users WHERE username = ? AND 
                          (password IS NULL OR password = ?)