Commandobject.executenonquery() and Commandobject.executereader() give different results for count(*)

451 views Asked by At

I'm trying to create a login page and when i give executereader it works and when i give executenonquery it returns a -1 value instead of 1.

This return -1 on cmd.executenonquery()

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

Below code with 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();

Code with 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();
2

There are 2 answers

4
Amarnath Balasubramanian On

ExecuteNonQuery

ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations. This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements. (Read More about ExecuteNonQuery)

SqlCommand.ExecuteNonQuery MSDN Documentation

ExecuteReader

Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last.(Read More about ExecuteReader)

SqlCommand.ExecuteReader MSDN Documentation

0
Piotr Perak On

Your ExecuteReader doesn't work either. You don't check whether select returned 1 but whether select returned any rows. And it always does. If no match is found it will return 1 row containing 0 as result.

ExecuteNonQuery is not appropriate because you are querying!

You should use ExecuteScalar instead.

Also you should be using 'using' construct or try finally to properly dispose of SqlConnection and SqlCommand.