ExecuteNonQuery
ExecuteScalar
- Used mainly for action queries(insert,delete,update,create,alter).
- Returns an int value indicating the number of affected rows.
- Return value is optional and can be assigned to an integer variable.
public void updateEmail()
{
SqlConnection con = new SqlConnection(connString);
String sqlQuery = "UPDATE Employee SET email='a@b.com' WHERE id=1;
SqlCommand cmd = new SqlCommand(sqlQuery, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
}
}
ExecuteScalar
- Used in queries where we have to read a single value.
- Returns an object.
- Return value is compulsory and should be assigned to a variable of required type.
Example:
public int getSomeNumber()
{
int count=0;
SqlConnection con = new SqlConnection(connString);
String sqlQuery = "SELECT COUNT(*) FROM dbo.myTable";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
try
{
con.Open();
//return type is System.Object, a typecast is must
count = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
}
return count;
}
That’s it!!…..Happy Programming...
No comments:
Post a Comment