-1

ログインページを作成しようとしていますが、executereader を指定すると機能し、executenonquery を指定すると 1 ではなく -1 の値が返されます。

これは、cmd.executenonquery() で -1 を返します。

SqlCommand cmd = new SqlCommand("select Count(*) from userDb where username= '"+txtusername.Text+"' and password= '"+txtpassword.Text+"'", con);

executereader() を使用した以下のコード

    SqlCommand cmd = new SqlCommand("select Count(*) from userDb where username= @p1 and password= @p2", con);

**Complete Code**
SqlCommand cmd = new SqlCommand("select Count(*) from userDb where username= @p1 and password= @p2", con);
        cmd.Parameters.AddWithValue("@p1", txtusername.Text);
        cmd.Parameters.AddWithValue("@p2", txtpassword.Text);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read()==true)
        {
            FormsAuthentication.RedirectFromLoginPage(txtusername.Text, CheckBox1.Checked);
        }
        else
        {
            lbldisplay.Text = "Username and Password Do not Match";
        }
        con.Close();

executenonquery を使用したコード

SqlCommand cmd = new SqlCommand("select Count(*) from userDb where username= '"+txtusername.Text+"' and password= '"+txtpassword.Text+"'", con);
            con.Open();
            int i = executenonquery();
            if (i == 1)
            {
                FormsAuthentication.RedirectFromLoginPage(txtusername.Text, CheckBox1.Checked);
            }
            else
            {
                lbldisplay.Text = "Username and Password Do not Match";
            }
            con.Close();
4

2 に答える 2

1

あなたの ExecuteReader も機能しません。select が 1 を返したかどうかはチェックしませんが、select が行を返したかどうかはチェックしません。そして、それは常にそうです。一致するものが見つからない場合、結果として 0 を含む 1 行が返されます。

クエリを実行しているため、ExecuteNonQuery は適切ではありません。

代わりに ExecuteScalar を使用する必要があります。

また、「using」コンストラクトを使用するか、最終的に SqlConnection と SqlCommand を適切に破棄する必要があります。

于 2013-12-15T08:18:59.227 に答える