必须声明标量变量“@UserName”

Must declare the scalar variable "@UserName"

我必须做一个简单的登录,当你在浏览器中插入一个 (") 时不会崩溃,所以我需要参数化查询字符串,但由于某种原因,我收到一个错误消息:

Must declare the scalar variable "@UserName"

这是代码

private void DoSqlQuery() 
{
    try 
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RolaConnectionString"].ConnectionString);
        conn.Open();
        string checkUser = "select * from UserData where UserName = @UserName";
        SqlCommand com = new SqlCommand(checkUser, conn);
        com.Parameters.AddWithValue("@Username", txtUserName.Text.Trim());

        int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
        conn.Close();
        if (temp == 1)
        {
            conn.Open();
            string checkPassword = "select Password from UserData where UserName = @UserName";
            SqlCommand passConn = new SqlCommand(checkPassword, conn);
            com.Parameters.AddWithValue("@Username", txtUserName.Text.Trim());
            string password = passConn.ExecuteScalar().ToString();
            conn.Close();
            if (password == txtPassword.Text)
            {
                Session["New"] = txtUserName.Text;
                Response.Write("Password is correct");
                Response.Redirect("~/LoggedIn.aspx");
            }
            else
            {
                Response.Write("Password is not correct");
            }
        }
        else
        {
            Response.Write("Username is not correct");
        }
    }
    catch(Exception e)
    {
        Response.Write(e.ToString());
    }
}

您在内部 if 语句中引用了错误的命令:

string checkPassword = "select Password from UserData where UserName = @UserName";
SqlCommand passConn = new SqlCommand(checkPassword, conn);
com.Parameters.AddWithValue("@Username", txtUserName.Text.Trim());
^^^--  should be passConn 

因此,你的第二个命令永远不会添加参数,所以你得到了你提到的错误。区分大小写 可能 也是一个问题,但这取决于您的数据库的排序规则 - SQL 默认情况下服务器不区分大小写。

其他一些与您的问题无关的建议:

  • using 语句中包装命令和连接
  • 一次查询用户名和密码(WHERE UserName = @UserName AND Password = @Password)。黑客将首先搜索有效的用户名,然后尝试使用字典攻击来破解密码。尝试找到匹配的组合 难得多。
  • 不要以纯文本形式存储密码 - 使用 salted hash
  • 或者只使用内置的安全提供程序而不是自己滚动。