2012-09-27 114 views
0

我想通過匹配用戶名&密碼創建一個登錄帳戶。我想將結果保存在一個名爲result的局部變量中。當用戶登錄時,結果應該是1,但它總是返回-1。我的代碼如下......選擇查詢錯誤

protected void LoginBtn_Click(object sender, EventArgs e) 
    { 
     string Name = nameTextBox.Text; 
     string Password = passwordTextBox.Text; 
     nameTextBox.Text = ""; 
     passwordTextBox.Text = ""; 
     string connectionstring = @"Integrated Security=True;Initial Catalog=HMIS;Data Source=.\SQLEXPRESS"; 
     SqlConnection connection = new SqlConnection(connectionstring); 
     connection.Open(); 
     string selectquery = "Select ID from UsersInfo where UserName='" + @Name+ "' and Password='" + @Password + "'"; 
     SqlCommand cmd = new SqlCommand(selectquery, connection); 
     cmd.Parameters.AddWithValue("@UserName", Name); 
     cmd.Parameters.AddWithValue("@Password", Password); 
     //object result = cmd.ExecuteNonQuery(); 
     //if (result != null) 
     int result = (int)cmd.ExecuteNonQuery(); 
     if (result > 0) 

回答

0

您的參數名稱不正確@UserName,而在查詢字符串@Name被使用。

試試看看這個代碼。

protected void LoginBtn_Click(object sender, EventArgs e) 
{ 
    string Name = nameTextBox.Text; 
    string Password = passwordTextBox.Text; 
    nameTextBox.Text = ""; 
    passwordTextBox.Text = ""; 
    string connectionstring = @"Integrated Security=True;Initial Catalog=HMIS;Data Source=.\SQLEXPRESS"; 
    SqlConnection connection = new SqlConnection(connectionstring); 
    connection.Open(); 
    string selectquery = "Select ID from UsersInfo where UserName='" + @Name+ "' and Password='" + @Password + "'"; 
    SqlCommand cmd = new SqlCommand(selectquery, connection); 
    cmd.Parameters.AddWithValue("@Name", Name); 
    cmd.Parameters.AddWithValue("@Password", Password); 
    //object result = cmd.ExecuteNonQuery(); 
    //if (result != null) 
    int result = (int)cmd.ExecuteNonQuery(); 
    if (result > 0) 
+0

這段代碼有什麼好運? –

0

ExecuteNonQuery方法返回受INSERT,UPDATE或DELETE影響的行數。對於所有其他類型的語句,返回值爲-1。

改爲使用ExecuteReader方法。這將返回一個SqlDataReader,它具有一個HasRows屬性。 ExecuteNonQuery不應該用於SELECT語句。