登录控件asp.net和CS

时间:2013-10-30 22:48:24

标签: c# asp.net visual-studio-2010 login login-control

我对ASP.NET和SQL Server数据库以及使用Visual Studio 2010有疑问。问题在于登录控件cs部分。

我将表单与数据库相关联,需要将登录名和密码与DB中的名称进行比较,但行

SqlDataReader rdr = com.ExecuteReader(); 

说“user”

附近的语法有错误

是查询问题吗?

你能帮我吗?

private bool UserLogin(string userName, string password)
{
    // read the coonection string from web.config 
    string conString = ConfigurationManager.ConnectionStrings["MidLinData"].ConnectionString;

    using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(conString))
    {
        con.Open();
        //' declare the command that will be used to execute the select statement 
       // SqlCommand com = new SqlCommand("SELECT login FROM user WHERE userName = @login AND Password = @password", con);
        SqlCommand com = new SqlCommand("SELECT login FROM user WHERE userName = @login ", con);
        SqlCommand com2 = new SqlCommand("SELECT password FROM user WHERE password = @password ", con);
        // set the username and password parameters
        com.Parameters.Add("@login", SqlDbType.NVarChar).Value = userName;
        SqlDataReader rdr = com.ExecuteReader();
        //com.Parameters.Add("@password", SqlDbType.NVarChar).Value = password;
        string result = rdr[0].ToString();

        // execute the select statment 
        //  string result = Convert.ToString(com.ExecuteScalar());
        //' check the result 
        if (string.IsNullOrEmpty(result))
        {
            //invalid user/password , return flase 
            return false;
        }
        else
        {
            // valid login
            return true;
        } 

        return true;
    }
}

编译说:

  服务器错误。

     

关键字“user”附近的语法不正确。

     

描述:执行当前Web请求期间发生了未处理的异常。

     

请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

     

异常详细信息:System.Data.SqlClient.SqlException:关键字“user”附近的语法不正确。

     

来源错误:

     

第57行://设置用户名和密码参数
  第58行:com.Parameters.Add(“@ login”,SqlDbType.NVarChar).Value = userName;
  第59行:SqlDataReader rdr = com.ExecuteReader();
  第60行:com.Parameters.Add(“@ password”,SqlDbType.NVarChar).Value =密码;
  第61行:

     

源文件:c:\ Users \ annasolovjova \ Desktop \ visualStudioWebsite \ login.aspx.cs行:59

2 个答案:

答案 0 :(得分:0)

您可以将这两个命令组合在一起:

SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "SELECT login, password FROM user WHERE userName = @login and password = @password";
com.Parameters.AddWithValue("login", userName); 
com.Parameters.AddWithValue("password", password);

答案 1 :(得分:0)

user是SQL Server中的保留关键字 - 您最好选择将其用作表名!如果您坚持使用它,必须将其放在方括号中:

SqlCommand com = new SqlCommand("SELECT login FROM [user] WHERE userName = @login ", con);