2013-10-30 175 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);