2013-05-06 34 views
0

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

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 [email protected][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."; 
    } 

} 
} 
+0

您使用的访问?然后你必须使用OleDbCommand和相关的类。 Sql *类用于SqlServer。 – 2013-05-06 12:55:26

+0

查询使用参数'@ [ID]'(您可能只需要一个'?'作为位置参数!),但是您提供了另外两个参数。 – 2013-05-06 12:56:40

回答

0

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

string sql="Select * from admin_login where [email protected][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][email protected]"; 
SqlCommand cmd=new SqlCommand(sql,cn); 
cmd.Parameters.Add("@ID", SqlDbType.Int); 
cmd.Parameters["@ID"].Value = userID; 
当然

,更换这最后的“用户标识”由无论你的用户ID变量命名为...

0

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

应该是这样的

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;