选择查询错误

时间:2012-09-27 16:50:48

标签: c# sql-server-2005

我想通过匹配UserName&创建一个登录帐户密码。我想将结果保存在名为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) 

2 个答案:

答案 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) 

答案 1 :(得分:0)

ExecuteNonQuery方法返回受INSERT,UPDATE或DELETE影响的行数。对于所有其他类型的语句,返回值为-1。

请改用ExecuteReader方法。这将返回一个SqlDataReader,它具有HasRows属性。 不应将ExecuteNonQuery用于SELECT语句。