我收到此错误'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.";
}
}
}
答案 0 :(得分:0)
您使用的是“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);
by:
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;
当然,无论你的用户名变量是什么,都要用最后的'userID'替换......
答案 1 :(得分: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;