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) 
4

2 回答 2

0

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

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

于 2012-09-27T16:58:19.997 回答
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) 
于 2012-09-27T16:56:21.437 回答