Using Parameterized SQL Statements


You want to create and execute a SQL statement having parameters that are set dynamically.


Add parameters to the Command object's Parameters collection.

The sample code contains two event handlers and one method:


Sets up the sample by creating a DataTable containing all Customers data from Northwind. The default view of the table is bound to a Customers data grid on the form. The handler for the CurrentCellChanged event of the data grid is called to initialize the grid containing Orders with the data for the row selected by default in the Customers data grid.


Gets the CustomerID from the data grid when the rows selected in the data grid changes and calls the LoadOrderGrid( ) method to update the Orders displayed to match the selected Customer.

LoadOrderGrid( )

This method defines a parameterized SQL statement. A Command is built from the statement and the single parameter, @CustomerID is created and set to the customerId argument passed into the method. The Command is used by a DataAdapter to fill a DataTable with the Orders for the specified Customer. The default view of the table is bound to the Customers data grid on the form.

The C# code is shown in Example 2-30.

Example 2-30. File: UsingParameterizedQueriesForm.cs

// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

// Table name constants
private const String CUSTOMERS_TABLE = "Customers";
private const String ORDERS_TABLE = "Orders";

// . . . 

private void UsingParameterizedQueriesForm_Load(object sender,
 System.EventArgs e)
 String sqlText = "SELECT * FROM Customers";

 // Retrieve table with all customers.
 SqlDataAdapter da = new SqlDataAdapter(sqlText,
 DataTable dt = new DataTable(CUSTOMERS_TABLE);

 // Bind the default view of the Customers table to the customers grid.
 customerDataGrid.DataSource = dt.DefaultView;
 // Fire the CurrentCellChanged event to refresh the orders grid.
 customerDataGrid_CurrentCellChanged(null, null);

private void customerDataGrid_CurrentCellChanged(object sender,
 System.EventArgs e)
 // Get the current row in the customers grid.
 int row = customerDataGrid.CurrentRowIndex;
 // Get the customer ID from the view.
 String customerId =
 Table.Rows[row][0].ToString( );
 // Retrieve the orders for the customer.

private void LoadOrderGrid(String customerId)
 String sqlText = "SELECT * FROM Orders " +
 "WHERE CustomerID = @CustomerID";

 // Create a connection and parameterized command.
 SqlConnection conn = new SqlConnection(
 SqlCommand cmd = new SqlCommand(sqlText, conn);
 // Add the CustomerID parameter and set its value.
 cmd.Parameters.Add("@CustomerID", SqlDbType.NChar, 5);
 cmd.Parameters["@CustomerID"].Value = customerId;

 // Get the Orders result set for the Customer.
 SqlDataAdapter da = new SqlDataAdapter(cmd);
 DataTable dt = new DataTable(ORDERS_TABLE);

 // Bind the default view of the orders table to the orders grid.
 orderDataGrid.DataSource = dt.DefaultView; 
 // Set the caption of the orders grid.
 orderDataGrid.CaptionText = "Orders [CustomerID: " + customerId + "]";


Parameterized queries allow one or more parameters to be replaced at runtime using Parameter objects in the ParameterCollection class of the Command object. These can also be the Command classes exposed by the DataAdapter . Using parameters is both easier than and less prone to errors than dynamically building queries. You're not responsible for creating delimeters such as single quotes around strings and pound signs around dates. Code is reusable and not specific to the data provider.

The SQL Server data provider uses the parameter names in the query and order is not important. The OLE DB data provider uses positional parameter markers, the question mark (?), and order is important. Consult the documentation for other .NET data providers for information about using parameters in queries.

Connecting to Data

Retrieving and Managing Data

Searching and Analyzing Data

Adding and Modifying Data

Copying and Transferring Data

Maintaining Database Integrity

Binding Data to .NET User Interfaces

Working with XML

Optimizing .NET Data Access

Enumerating and Maintaining Database Objects

Appendix A. Converting from C# to VB Syntax

ADO. NET Cookbook
ADO.NET 3.5 Cookbook (Cookbooks (OReilly))
ISBN: 0596101406
EAN: 2147483647
Year: 2002
Pages: 222
Authors: Bill Hamilton © 2008-2020.
If you may any questions please contact us: