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()?
MySqlCommand. ExecuteNonQuery Method. Executes a SQL statement against the connection and returns the number of rows affected.
The connection's current state is closed. ExecuteNonQuery requires an open and available Connection.
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.).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With