ExecuteScalar vs ExecuteNonQuery

ExecuteScalar Vs ExecuteNonQuery
 
   
 
 
          
 
ExecuteScalar Method

Namespace:
  System.Data.SqlClient

Return DataType
: System.Object (returns a single value)

Use : Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Example:
public int getSomeProdId()
{
        int count=0;
        SqlConnection conn = new SqlConnection(connString))
        String sqlQuery = “SELECT COUNT(*) FROM dbo.region”;
        SqlCommand cmd = new SqlCommand(sqlQuery, conn);
        try
        {
            conn.Open();
            //Since return type is System.Object, a typecast is must
            count = (Int32)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
         finally
         {
            conn.Close();
         }
         return count;
}

ExecuteNonQuery Method

Namespace:  System.Data.SqlClient

Return DataType
: System.Int32 (number of rows affected)

Use : You can use the ExecuteNonQuery to perform catalog operations by executing UPDATE, INSERT, or DELETE statements.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1.

Example:
public void UpdateEmployeeEmail()
{
        SqlConnection conn = new SqlConnection(connString))
        String sqlQuery = “UPDATE Employee SET empemail=’suresh.paldia@xyz.com’ WHERE empid=4;
        SqlCommand cmd = new SqlCommand(sqlQuery, conn);
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
         finally
         {
            conn.Close();
         }
         return count;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: