Using Parameterized SQL Statements
Số trang: 3
Loại file: pdf
Dung lượng: 14.33 KB
Lượt xem: 2
Lượt tải: 0
Xem trước 2 trang đầu tiên của tài liệu này:
Thông tin tài liệu:
[ Team LiB ] Recipe 2.21 Using Parameterized SQL Statements Problem You want to create and execute a SQL statement having parameters that are set dynamically. Solution Add parameters to the Command objects Parameters collection.
Nội dung trích xuất từ tài liệu:
Using Parameterized SQL Statements[ Team LiB ]Recipe 2.21 Using Parameterized SQL StatementsProblemYou want to create and execute a SQL statement having parameters that are setdynamically.SolutionAdd parameters to the Command objects Parameters collection.The sample code contains two event handlers and one method:Form.Load 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.DataGrid.CurrentCellChanged 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 constantsusing System;using System.Configuration;using System.Data;using System.Data.SqlClient;// Table name constantsprivate 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 usingParameter objects in the ParameterCollection class of the Command object. These canalso be the Command classes exposed by the DataAdapter. Using parameters is botheasier than and less prone to errors than dynamically building queries. Youre notresponsible for creating delimeters such as single quotes around strings and pound signsaround 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 notimportant. The OLE DB data provider uses positional parameter markers, the questionmark (?), and order is important. Consult the documentation for other .NET dataproviders for information about using parameters in queries.[ Team LiB ]
Nội dung trích xuất từ tài liệu:
Using Parameterized SQL Statements[ Team LiB ]Recipe 2.21 Using Parameterized SQL StatementsProblemYou want to create and execute a SQL statement having parameters that are setdynamically.SolutionAdd parameters to the Command objects Parameters collection.The sample code contains two event handlers and one method:Form.Load 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.DataGrid.CurrentCellChanged 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 constantsusing System;using System.Configuration;using System.Data;using System.Data.SqlClient;// Table name constantsprivate 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 usingParameter objects in the ParameterCollection class of the Command object. These canalso be the Command classes exposed by the DataAdapter. Using parameters is botheasier than and less prone to errors than dynamically building queries. Youre notresponsible for creating delimeters such as single quotes around strings and pound signsaround 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 notimportant. The OLE DB data provider uses positional parameter markers, the questionmark (?), and order is important. Consult the documentation for other .NET dataproviders for information about using parameters in queries.[ Team LiB ]
Tìm kiếm theo từ khóa liên quan:
công nghệ thông tin kỹ thuật lập trình Oreilly Ado Dot Net Cookbook Ebook-Lib Using Parameterized SQL StatementsGợi ý tài liệu liên quan:
-
52 trang 430 1 0
-
Top 10 mẹo 'đơn giản nhưng hữu ích' trong nhiếp ảnh
11 trang 314 0 0 -
74 trang 299 0 0
-
96 trang 293 0 0
-
Báo cáo thực tập thực tế: Nghiên cứu và xây dựng website bằng Wordpress
24 trang 289 0 0 -
Đồ án tốt nghiệp: Xây dựng ứng dụng di động android quản lý khách hàng cắt tóc
81 trang 281 0 0 -
EBay - Internet và câu chuyện thần kỳ: Phần 1
143 trang 275 0 0 -
Tài liệu dạy học môn Tin học trong chương trình đào tạo trình độ cao đẳng
348 trang 269 1 0 -
Kỹ thuật lập trình trên Visual Basic 2005
148 trang 265 0 0 -
Tài liệu hướng dẫn sử dụng thư điện tử tài nguyên và môi trường
72 trang 265 0 0