2013-10-30 173 views
1

我有一个关于ASP.NET和SQL Server数据库和使用Visual Studio 2010的问题。问题是关于登录控件cs部分。登录控制asp.net和CS

我联系我与数据库的形式,需要比较与那些在DB登录名和密码,但行

SqlDataReader rdr = com.ExecuteReader(); 

说有语法附近“用户”

它是一个错误查询问题?

你能帮助我吗?

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; 
    } 
} 

编译器说:

Server Error in '/visualStudioWebsite' Application.

Incorrect syntax near the keyword 'user'.

Description: An unhandled exception occurred during the execution of the current web request.

Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'user'.

Source Error:

Line 57: // set the username and password parameters
Line 58: com.Parameters.Add("@login", SqlDbType.NVarChar).Value = userName;
Line 59: SqlDataReader rdr = com.ExecuteReader();
Line 60: com.Parameters.Add("@password", SqlDbType.NVarChar).Value = password;
Line 61:

Source File: c:\Users\annasolovjova\Desktop\visualStudioWebsite\login.aspx.cs Line: 59

+0

张贴从编译器错误信息可能会有帮助。 – vdbuilder

+0

刚刚编辑帖子 –

回答

0

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

SqlCommand com = new SqlCommand("SELECT login FROM [user] WHERE userName = @login ", con); 
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);