ADO.NET Bound Parameters
The following C# code fragment executes a SQL INSERT statement that adds new sales to the sales table in the pubs database. The INSERT statement is parameterized to provide better performance, since the statement object needs to be parsed only once on the server.
// Create a Command object for the SQL statement Statementstatement
=connection
.CreateCommand( );statement
.CommandText = "INSERT INTO SALES(stor_id, ord_num, ord_date, qty, payterms, title_id) " + "VALUES(@stor_id, @ord_num, @ord_date, @qty, @payterms, @title_id)"; //Prepare the statement on the serverstatement
.Prepare( ); // Declare parameters that will be bound {Odbc|OleDb|Sql}Parameter stor_id, ord_num, ord_date, qty, payterms, title_id; stor_id =statement
.Parameters.Add( "@stor_id", DbType.String ); ord_num =statement
.Parameters.Add( "@ord_num", DbType.String ); ord_date =statement
.Parameters.Add( "@ord_date", DbType.DateTime); qty =statement
.Parameters.Add( "@qty", DbType.Int16 ); payterms =statement
.Parameters.Add( "@payterms", DbType.String ); title_id =statement
.Parameters.Add( "@title_id", DbType.String ); while( GetNextSale(stor_id, ord_num, ord_date, qty, payterms, title_id) ) { // Execute the statement int result =statement
.ExecuteNonQuery( ); if( result != 1 ) { // If result isn't 1, then the insert failed. System.Console.WriteLine( "The INSERT failed." ); break; } }
Use the following steps to execute statements with bound parameters in ADONET:
As done in previous sections, ...
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.