c# - sql 数据库错误 "Must declare the scalar variable"

标签 c# asp.net sql

我的登录系统有问题。我制作了一个运行良好的简单系统,但我想让它更高级,并根据用户的 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/

相关文章:

c# - Web 服务命名空间动态命名

c# - 获取 azure 上虚拟文件夹中的 blob (BlobService.ListBlobs) (C#)

c# - 在回调中重用回调时如何防止 StackOverflowException?

c# - 正则表达式日期和时间

mysql - 同时使用分组列和非分组列

c# - 从托管 C++ DLL 使用 C# 程序集时崩溃

c# - asp.net core 1 appsettings.production.json 不更新连接字符串

ASP.NET/MVC Bundler 缓存不起作用

SQL isset 并且不显示空白 'cells'

sql - 为什么 Microsoft SSMS 语法突出显示单词 "configuration"?