- ExecuteReader : Use for accessing data. It provides a forward-only, read-only, connected recordset.
- ExecuteNonQuery : Use for data manipulation, such as Insert, Update, Delete.
- ExecuteScalar : Use for retriving 1 row 1 col. value., i.e. Single value. eg: for retriving aggregate function. It is faster than other ways of retriving a single value from DB.
sir according to my knowledge
ReplyDeleteExecuteNonQuery : Use for only select command ...
may be i m wrong ....sir wats ur opinion ????
@Gopal--ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating Stored Procedures and Views perform by ExecuteNonQuery() . Also Data Manipulation tasks like Insert , Update and Delete perform by ExecuteNonQuery().
ReplyDeleteUpdate example ---
ReplyDeleteusing System;
using System.Data; // Use ADO.NET namespace
using System.Data.SqlClient; // Use SQL Server data provider namespace
using System.Collections.Generic;
using System.Text;
class Program {
static void Main(string[] args) {
SqlConnection thisConnection = new SqlConnection(
@"Server=(local)\sqlexpress;Integrated Security=True;" +
"Database=northwind");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "UPDATE Products SET " +
"UnitPrice=UnitPrice*1.05 WHERE SupplierId=12";
int rowsAffected = thisCommand.ExecuteNonQuery();
Console.WriteLine("Rows Updated = {0}", rowsAffected);
thisConnection.Close();
}
}
See this example to insert,update,delete--
ReplyDeleteusing System;
using System.Data;
using System.Data.SqlClient;
class ExecuteInsertUpdateDelete
{
public static void DisplayRow(SqlCommand mySqlCommand, string ID){
mySqlCommand.CommandText ="SELECT ID, FirstName FROM Employee WHERE ID = '" + ID + "'";
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
while (mySqlDataReader.Read())
{
Console.WriteLine("mySqlDataReader[\" ID\"] = " +
mySqlDataReader["ID"]);
Console.WriteLine("mySqlDataReader[\" FirstName\"] = " +
mySqlDataReader["FirstName"]);
}
mySqlDataReader.Close();
}
public static void Main()
{
SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText ="INSERT INTO Employee (ID, FirstName) VALUES (" +
" 9, 'Jason')";
mySqlConnection.Open();
int numberOfRows = mySqlCommand.ExecuteNonQuery();
Console.WriteLine("Number of rows added = " + numberOfRows);
DisplayRow(mySqlCommand, "9");
mySqlCommand.CommandText = "UPDATE Employee SET FirstName = 'New' WHERE ID = '9'";
numberOfRows = mySqlCommand.ExecuteNonQuery();
Console.WriteLine("Number of rows updated = " + numberOfRows);
DisplayRow(mySqlCommand, "9");
mySqlCommand.CommandText ="DELETE FROM Employee WHERE ID = '9'";
numberOfRows = mySqlCommand.ExecuteNonQuery();
Console.WriteLine("Number of rows deleted = " + numberOfRows);
mySqlConnection.Close();
}
}