O'Reilly logo

SQL in a Nutshell by Kevin Kline

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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
Statement statement = 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 server
statement.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:

  1. As done in previous sections, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required