Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does cmd.ExecuteNonQuery() do in my program

string connection = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=D:\\it101\\LoginForm\\App_Data\\registration.mdb";

string query = "INSERT INTO [registration] ([UserID] , [Name] , [Contact_no] , [City]) values (123, 'abc' ,12345, 'pqr')";

OleDbConnection con = new OleDbConnection(connection);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;

con.Open();
cmd.ExecuteNonQuery();

And what if i do not write cmd.ExecuteNonQuery() at the end of my program? And if the query needs to be executed why is it written executeNonquery() instead of executeQuery()?

like image 535
Parth Avatar asked Mar 03 '14 09:03

Parth


People also ask

What does CMD ExecuteNonQuery return?

MySqlCommand. ExecuteNonQuery Method. Executes a SQL statement against the connection and returns the number of rows affected.

Does ExecuteNonQuery open connection?

The connection's current state is closed. ExecuteNonQuery requires an open and available Connection.

What is difference between ExecuteReader and ExecuteNonQuery?

ExecuteReader is used for any result set with multiple rows/columns (e.g., SELECT col1, col2 from sometable ). ExecuteNonQuery is typically used for SQL statements without results (e.g., UPDATE, INSERT, etc.).

What is difference between ExecuteScalar and ExecuteNonQuery?

ExecuteScalar() only returns the value from the first column of the first row of your query. ExecuteReader() returns an object that can iterate over the entire result set. ExecuteNonQuery() does not return data at all: only the number of rows affected by an insert, update, or delete.


2 Answers

if we want to deal with database two things will happen i.e; Modifying,Retrieving

Modifying:

In Modifying Section,we have Insert, Delete ,Update,...queries.so for this we need to use ExecuteNonQuery command.why because we are not querying a database, we are modifying.

syntax:

cmd.ExecuteNonQuery Method

Retrieving:

In this we query a database by using Select Statement.For this we use ExecuteReader(),ExecuteScalar()

If select Query return more than one record.we need to use ExecuteReader()

If select Query return only one record.we need to use ExecuteScalar()

syntax:

cmd.ExecuteReader() Method

cmd.ExecuteScalar() Method

The above statements(ExecuteReader(),ExecuteScalar(),SqlCommand.ExecuteNonQuery()) are used to execute command statement which you give in SqlCommand.If you dont use, your command not be executed.

like image 88
Ajay Avatar answered Oct 21 '22 12:10

Ajay


ExecuteNonQuery executes a query that is not expected to produce any results (e.g. an UPDATE, or INSERT).

ExecuteQuery executes a query that is supposed to produce a result (i.e. a SELECT).

If you do not write ExecuteNonQuery at the end, your query won't be executed.

like image 23
RB. Avatar answered Oct 21 '22 13:10

RB.