Executing an ADO.NET Statement
The following code fragment provides the syntax for executing a SQL INSERT statement using ADO.NET:
{Odbc|OleDb|Sql}Commandstatement
=connection
.CreateCommand( );statement
.CommandText = "INSERT INTO authors(au_id, au_lname, " + " au_fname, contract) " + "VALUES ('xyz', 'Brown', 'Emmit', 1)"; introwsInserted
=statement
.ExecuteNonQuery( );statement
.Close( );
To execute a statement using ADO.NET, take the following steps:
Create an ADO.NET
Command
object.SqlCommand
is used for access to Microsoft SQL Server,OdbcCommand
is used for ODBC data sources, andOleDbCommand
for OLE-DB data sources.{Odbc|OleDb|Sql}Command
statement
=connection
.CreateCommand( );After creating the appropriate
Command
object, a SQL statement needs to be associated with theCommand
before it can be executed.statement
.CommandText = "INSERT INTO authors(au_id, au_lname, " + " au_fname, contract) " + "VALUES ('xyz', 'Brown', 'Emmit', 1)";After assignment of the SQL statement, the
Command
object is ready for execution.int
rowsInserted
=statement
.ExecuteNonQuery( );There are three methods that can be used to execute ADO.NET
Command
objects:ExecuteReader
: Executes SQL statements that return rows, such as SELECT statements. The return value is an ADO.NETDataReader
object.ExecuteNonQuery
: Executes SQL statements that do not typically return result sets, such as INSERT, DELETE, or UPDATE statements. The return value is an integer value equal to the number of rows affected by the ...
Get SQL in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.