我的登录系统有问题。我制作了一个运行良好的简单系统,但我想让它更高级,并根据用户的 UserType
显示不同的起始页。但是,我遇到了以下错误:“必须声明标量变量@UserType。”
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class LoginwithEncryption : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(
"select * from dbo.UserInfo where Login =@Login and UserType=@UserType and Password=@Password and UserType=@UserType", con);
cmd.Parameters.AddWithValue("@Login", txtUserName.Text);
cmd.Parameters.AddWithValue("@Password", txtPWD.Text+".123");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
int usertype = Convert.ToInt32(dt.Rows[0]["UserType"]);
if (usertype == 1)
{
Response.Redirect("StartPage.aspx");
}
else if (usertype == 2)
{
Response.Redirect("DiferentStartPage.aspx");
}
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation",
"<script language='javascript'>alert('Invalid UserName and Password')</script>");
}
}
}
最佳答案
如错误所述:必须声明标量变量“@UserType”
换句话说,SQL命令有一个参数为@UserType
,但是参数集合中没有声明参数。
SqlCommand cmd = new SqlCommand(
"select * from dbo.UserInfo where Login =@Login and UserType=@UserType and Password=@Password and UserType=@UserType", con);
cmd.Parameters.AddWithValue("@Login", txtUserName.Text);
cmd.Parameters.AddWithValue("@Password", txtPWD.Text+".123");
为@UserType
参数添加另一个参数:
cmd.Parameters.AddWithValue("@UserType", "User Type");
此外,SQL 包含对 @UserType
的重复引用:
select * from dbo.UserInfo
where Login=@Login
and UserType=@UserType
and Password=@Password
and UserType=@UserType
应该是:
select * from dbo.UserInfo
where Login=@Login
and Password=@Password
and UserType=@UserType
关于c# - sql 数据库错误 "Must declare the scalar variable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20647538/