.NET FAQs Unleashed!
 

I AM BIG BROTHER - SPY SOFTWARE - SECRETLY RECORDS EMAIL, CHAT & MORE

What is the difference between ExecuteScalar and ExecuteNonQuery? What is ExecuteReader?

ExecuteScalar - Returns only one value after execution of the query. It returns the first field in the first row. This is very light-weight and is perfect when all your query asks for is one item. This would be excellent for receiving a count of records (Select Count(*)) in an sql statement, or for any query where only one specific field in one column is required.

ExecuteNonQuery - This method returns no data at all. It is used majorly with Inserts and Updates of tables. It is used for execution of DML commands.

Example:
SqlCommand cmd = new SqlCommand("Insert Into t_SomeTable Values('1','2')",con);
//note that con is the connection object
con.Open();
cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed

ExecuteReader - This method returns a DataReader which is filled with the data that is retrieved using the command object. This is known as a forward-only retrieval of records. It uses our SQL statement to read through the table from the first to the last record.

1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23