[ Team LiB ] |
Recipe 2.21 Using Parameterized SQL StatementsProblemYou want to create and execute a SQL statement having parameters that are set dynamically. SolutionAdd parameters to the Command object's Parameters collection. The sample code contains two event handlers and one method:
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, ConfigurationSettings.AppSettings["Sql_ConnectString"]); DataTable dt = new DataTable(CUSTOMERS_TABLE); da.Fill(dt); // 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 = ((DataView)customerDataGrid.DataSource). Table.Rows[row][0].ToString( ); // Retrieve the orders for the customer. LoadOrderGrid(customerId); } private void LoadOrderGrid(String customerId) { String sqlText = "SELECT * FROM Orders " + "WHERE CustomerID = @CustomerID"; // Create a connection and parameterized command. SqlConnection conn = new SqlConnection( ConfigurationSettings.AppSettings["Sql_ConnectString"]); 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); da.Fill(dt); // 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 + "]"; } DiscussionParameterized 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. |
[ Team LiB ] |