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()?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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.
Method 3
SqlCommand.ExecuteNonQuery Method
Executes statement against the connection and returns the number of rows affected.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command.
Runs the given SQL statement and returns a single SQLServerResultSet object.
If you want to execute your query you should use ExecuteNonQuery
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0