2013-01-14 81 views
3

我想獲取我的帳戶表的行數,以便我可以登錄帳戶但​​MySQL參數不添加值。MySQL參數不添加值

這裏是我的代碼:

public int MyMethod(string username, string password) 
{ 
    int count = 0; 
    string query = "SELECT * FROM accounts WHERE username = '?user' AND password = '?pass' LIMIT 1;"; 

    using (MySqlCommand cmd = new MySqlCommand(query, connector)) 
    { 
     cmd.Parameters.Add(new MySqlParameter("?user", username)); 
     cmd.Parameters.Add(new MySqlParameter("?pass", password)); 

     count = int.Parse(cmd.ExecuteScalar().ToString()); 
    } 

    return count; 
} 

回答

4

參數佔位不應該用單引號,因爲它迫使它成爲一個值,而不是一個參數了,試試這個封閉的,

public int MyMethod(string username, string password) 
{ 
    int count = 0; 
    string query = "SELECT * FROM accounts WHERE username = @user AND password = @pass LIMIT 1;"; 

    using (MySqlCommand cmd = new MySqlCommand(query, connector)) 
    { 
     cmd.Parameters.Add(new MySqlParameter("@user", username)); 
     cmd.Parameters.Add(new MySqlParameter("@pass ", password)); 

     connector.Open(); // don't forget to open the connection 
     count = int.Parse(cmd.ExecuteScalar().ToString()); 
    } 

    return count; 
} 
1

我相信你想要做這樣的事情:

SELECT COUNT(*) FROM accounts WHERE username = '?user' AND password = '?pass'; 

這將讓你的有指定的用戶名和密碼的記錄數。

1

嘗試添加的參數是這樣的:

cmd.Parameters.AddWithValue("@user", username); 
cmd.Parameters.AddWithValue("@pass", password); 
1

試試這個: '?MYVARIABLE' @myVariable代替SELECT COUNT(*)改爲選擇*

public int MyMethod(string username, string password) 
{ 
    int count = 0; 
    string query = "SELECT count(*) FROM accounts WHERE username = @user AND password = @pass LIMIT 1;"; 

    using (MySqlCommand cmd = new MySqlCommand(query, connector)) 
    { 
     connector.Open(); 
     cmd.Parameters.AddWithValue("@user", username); 
     cmd.Parameters.AddWithValue("@pass", password);  
     count = int.Parse(cmd.ExecuteScalar().ToString()); 
    } 

    return count; 
}