SQLCommand.ExecuteScalar() - 为什么它抛出一个System.NullReferenceException?抛出、ExecuteScalar、SQLCommand、Syste

2023-09-03 05:59:56 作者:三分钟的热度

任何人都可以发现这可能是错误的以下功能:

Could anyone notice what could be wrong with the following function:

public string Login(string username, string password)
    {
        string result = "";
        string select = "SELECT user_id FROM [user] WHERE username = @username AND password = @password";
        SqlConnection conn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(select, conn);
        cmd.Parameters.AddWithValue("username", username);
        cmd.Parameters.AddWithValue("password", password);
        int userID = 0;
        try
        {
            conn.Open();
            userID = (int)cmd.ExecuteScalar();
            if(userID > 0)
            {
                result = addSession(userID);
            }
        }
        catch(Exception ex)
        {
            string sDummy = ex.ToString();
        }
        return result;
    }

不知道为什么行`用户ID =(INT)cmd.ExecuteScalar();抛出一个异常。

Don't know why the line `userID = (int)cmd.ExecuteScalar(); throws an exception.

感谢

推荐答案

很可能是在表中没有行与该用户/密码。该文档的的ExecuteScalar 说它返回null,如果结果集是空的,你可以不投空为int。

Most likely there is no row in the table with that user/password. The docs for ExecuteScalar say that it returns null if the result set is empty, and you can't cast null to int.

 
精彩推荐
图片推荐