Differentiate ExecuteNonQuery and ExecuteSclar and give the example for both?
Manoj Kumar
ExecuteScalar return object type value but ExecuteNonQuery return int value
execute scalar return a single value and execute nonquery does not return data at all: only the number of rows affected by an insert, update, or delete.
ExcuteNonQuery is used for Except Retrieve(Select) the data from DB EX:using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TMSConnectionString"].ConnectionString)){con.Open();string msg = string.Empty;string lstr = "Insert Into UserInfo1 (Name) VALUES(@Name)";SqlCommand cmd = new SqlCommand(lstr, con);cmd.Parameters.AddWithValue("@Name", txtname.Text);int recordcount = cmd.ExecuteNonQuery();if (recordcount>0){msg = "Record Saved sucessfully";} }ExecuteScalar:It will retrieve the first row and column get from DB using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TMSConnectionString"].ConnectionString)){con.Open();string msg = string.Empty;string lstr = "Select Name from UserInfo1";SqlCommand cmd = new SqlCommand(lstr, con);string result = (string)cmd.ExecuteScalar();if (!string.IsNullOrEmpty(result)){}
Executenonquery is used to insert update &delete while ExecuteScaler is used to fetch one object only
ExecuteNonQuery working with Action Query like Insert,Delete,UpdateExecuteSclar working with NonAction Query plus Agrigate Function like Select Conut(*),Select Max,Select Min
- **ExecuteScalar** is going to be the typeof query which will be returning asingle value. *An example would be returning a generated id after inserting.*`INSERT INTO my_profile (Address) VALUES ('123 Fake St.');SELECT CAST(scope_identity() AS int)`- **ExecuteReader** gives you a data readerback which will allow you to read allof the columns of the results a rowat a time. *An example would be pulling profile information for one or more users.*`SELECT * FROM my_profile WHERE id = '123456'`- **ExecuteNonQuery** is any SQL which isn't returning values, but isactually performing some form of worklike inserting deleting or modifyingsomething. *An example would be updating a user's profile in the database.*`UPDATE my_profile SET Address = '123 Fake St.' WHERE id = '123456'`
Scaler returns single object
ExecuteNonQuery is used to select more data while ExecuteScaler is used to select only one object