我必须做一个简单的登录,当你插入浏览器时不会崩溃(")所以我需要参数化查询字符串,但由于某种原因,我得到一个错误说:
必须声明标量变量" @ 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());
}
}
答案 0 :(得分:0)
您在内部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 Server不区分大小写。
与您的问题无关的其他一些建议:
using
语句中包装命令和连接WHERE UserName = @UserName AND Password = @Password
)。黑客将首先搜索有效的用户名,然后尝试使用字典攻击来破解密码。试图找到匹配的组合很多更难。