0

UserNameとPasswordを照合してログインアカウントを作成したい。結果を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

クエリ文字列で @Name が使用されているのに対し、パラメーター名は間違った @UserName でした。

このコードを試してください。

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 に答える