【问题标题】:how to remove error Incorrect syntax near 'nvarchar'. Must declare the scalar variable "@"如何删除错误 'nvarchar' 附近的语法不正确。必须声明标量变量“@”
【发布时间】:2013-05-06 12:48:59
【问题描述】:

我收到此错误“nvarchar”附近的语法不正确。必须声明标量变量“@”。我正在使用下面提到的代码。这里 SACALOGIN.MDF 是数据库名 admin_login 是表名。用户名和密码是表格列,admin1.aspx 是另一个网页...请帮忙,因为它让我很头疼.....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.Configuration.Common;
using System.Web.Configuration.Internal;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
   protected void btnSubmit_Click(object sender, EventArgs e)
{

    SqlConnection cn=new SqlConnection();
    cn.ConnectionString = 
      WebConfigurationManager.ConnectionStrings["SACALOGIN.MDF"].ConnectionString;
    cn.Open();
    string sql="Select * from admin_login where ID=@[ID]";
    SqlCommand cmd=new SqlCommand(sql,cn);
    cmd.Parameters.AddWithValue("@[User-Name]",txtUserName.Text);
    cmd.Parameters.AddWithValue("@Password",txtPWD.Text);
    SqlDataReader dr=cmd.ExecuteReader();
    bool found=false;
    if(dr.Read())
    {
        found=true;
        cn.Close();
        if(found)
        {
            Response.Redirect("admin1.aspx");
           }
        else 
            lblMessage.Text="Sorry! Invalid User Id.";
    }

}
}

【问题讨论】:

  • 您在使用 Access 吗?然后你必须使用 OleDbCommand 和相关的类。 Sql* 类用于 SqlServer。
  • 查询使用参数@[ID](您可能只需要? 作为位置参数!),但您提供另外两个。

标签: asp.net


【解决方案1】:

您正在使用“ID”参数,但您添加到命令中的唯一参数是“@user-name”和“@Password”。尝试替换:

string sql="Select * from admin_login where ID=@[ID]";
SqlCommand cmd=new SqlCommand(sql,cn);
cmd.Parameters.AddWithValue("@[User-Name]",txtUserName.Text);
cmd.Parameters.AddWithValue("@Password",txtPWD.Text);

作者:

string sql="Select * from admin_login where [ID]=@ID";
SqlCommand cmd=new SqlCommand(sql,cn);
cmd.Parameters.Add("@ID", SqlDbType.Int);
cmd.Parameters["@ID"].Value = userID;

当然,用您的用户 ID 变量命名的任何名称替换最后一个“用户 ID”...

【讨论】:

    【解决方案2】:

    我认为你的代码永远不会工作。

    应该是这样的

    SqlConnection cn=new SqlConnection();
    cn.ConnectionString =                                                                                                  W         WebConfigurationManager.ConnectionStrings["SACALOGIN.MDF"].ConnectionString;
    cn.Open();
    string sql="Select * from admin_login where [User-Name] = @Username and Password= @Password";
    SqlCommand cmd=new SqlCommand(sql,cn);
    cmd.Parameters.AddWithValue("@Username",txtUserName.Text);
    cmd.Parameters.AddWithValue("@Password",txtPWD.Text);
    SqlDataReader dr=cmd.ExecuteReader();
    bool found=false;
    

    【讨论】:

      猜你喜欢
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多