Netframwork 2.0 (phần 7) doc

50 315 0
Netframwork 2.0 (phần 7) doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Lesson 2: Working with Parameters in SQL Commands 275 The following code creates an Output parameter: ' VB Dim TotalCostParameter As New SqlParameter("@TotalCost", SqlDbType.Money) TotalCostParameter.Direction = ParameterDirection.Output // C# SqlParameter TotalCostParameter = new SqlParameter("@TotalCost", SqlDbType.Money); TotalCostParameter.Direction = ParameterDirection.Output; Adding Parameters to Command Objects Command objects have a Parameters property that represents a collection of parame- ters for that command (for example, the SqlParameter.Parameters property). After you create a parameter, you must add it to the Parameters collection of the Command object that will execute the SQL statement or stored procedure that uses the parameter. The following code illustrates how to add a parameter to a Command object (assuming the GetCostCommand already exists): ' VB GetCostCommand.Parameters.Add(TotalCostParameter) // C# GetCostCommand.Parameters.Add(TotalCostParameter); Lab: Working with Parameters In this lab you practice using parameters in Command objects. You will pass parame- ters to stored procedures as well as SQL statements. � Exercise 1: Creating and Executing a Parameterized SQL Statement For this exercise, create a form that executes a parameterized query by allowing the user to enter a value into a TextBox that will be passed to the database as the param- eter in a query. 1. Create a new Windows application and name it ParameterizedQueries. 2. Add a TextBox to the form and set the following properties: ❑ Name = CityTextBox ❑ Text = London 3. Add a second TextBox and set the following properties: ❑ Name = ResultsTextBox ❑ MultiLine = True 276 Chapter 6 Working with Data in a Connected Environment 4. Add a button and set the following properties. Now, the form should resemble Figure 6-3: ❑ Name = ExecuteSqlButton ❑ Text = Execute SQL Figure 6-3 Form with controls in preparation for executing the parameterized SQL statement 5. Double-click the Execute SQL button to create the button-click event handler and switch the form to code view. 6. Add references to the System.Data and System.Data.SqlClient namespaces. 7. Add code to create a connection on the form. At this point, your form code should look like the following (substitute a valid connection string for the NorthwindConnection): ' VB Imports System.Data Imports System.Data.SqlClient Public Class Form1 Private NorthwindConnection As New SqlConnection _ ("Data Source=<ValidServerName>;Initial Catalog=Northwind;Integrated Security=True") Private Sub ExecuteSqlButton_Click _ (ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles ExecuteSqlButton.Click End Sub End Class // C# using System; using System.Collections.Generic; Lesson 2: Working with Parameters in SQL Commands 277 using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace ParameterizedQueries { public partial class Form1 : Form { private SqlConnection NorthwindConnection = new SqlConnection ("Data Source=.\\sqlexpress;Initial Catalog=Northwind;Integrated Security=True"); public Form1() { InitializeComponent(); } private void ExecuteSqlButton_Click(object sender, EventArgs e) { } } } 8. Add the following code to the ExecuteSqlButton_Click method to create a new command object and set it to the parameterized query: ' VB ' Create a new Command object Dim CustomersByCityCommand As New SqlCommand ' Set the command properties CustomersByCityCommand.Connection = NorthwindConnection CustomersByCityCommand.CommandType = CommandType.Text CustomersByCityCommand.CommandText = & _ "SELECT CustomerID, CompanyName, City " & _ "FROM Customers " & _ "WHERE City = @City" // C# // Create a new Command object SqlCommand CustomersByCityCommand = new SqlCommand(); // Set the command properties CustomersByCityCommand.Connection = NorthwindConnection; CustomersByCityCommand.CommandType = CommandType.Text; CustomersByCityCommand.CommandText = "SELECT CustomerID, CompanyName, City " + "FROM Customers " + "WHERE City = @City"; 278 Chapter 6 Working with Data in a Connected Environment 9. Add the following code below the previous code (but still within the event han- dler) to create the parameter and assign it to the command: ' VB ' Create the @City parameter Dim CityParameter As New SqlParameter ' Set its name and data type CityParameter.ParameterName = "@City" CityParameter.SqlDbType = SqlDbType.NVarChar ' Since the city column in the database allows ' null values we can set the IsNullable property ' to allow null values. CityParameter.IsNullable = True ' Add the parameter to the Commmand object CustomersByCityCommand.Parameters.Add(CityParameter) // C# // Create the @City parameter SqlParameter CityParameter = new SqlParameter(); // Set its name and data type CityParameter.ParameterName = "@City"; CityParameter.SqlDbType = SqlDbType.NVarChar; // Since the city column in the database allows // null values we can set the IsNullable property // to allow null values. CityParameter.IsNullable = true; // Add the parameter to the Commmand object CustomersByCityCommand.Parameters.Add(CityParameter); 10. Now add the following code that will set the value of the parameter to whatever is typed into the text box, set the code to run the query, and display the results in the ResultsTextBox. (Add this code below the previously added code but con- tinue to keep it within the event handler.) ' VB ' Set the parameters value to the ' the text in the CityTextBox CityParameter.Value = CityTextBox.Text ' Create a StringBuilder to store the results of the query Dim results As New System.Text.StringBuilder ' You must open the connection before executing the command CustomersByCityCommand.Connection.Open() Lesson 2: Working with Parameters in SQL Commands 279 ' Assign the results of the SQL statement to a data reader Dim reader As SqlDataReader = CustomersByCityCommand.ExecuteReader While reader.Read For i As Integer = 0 To reader.FieldCount - 1 results.Append(reader(i).ToString & vbTab) Next results.Append(Environment.NewLine) End While ' Close the data reader and the connection reader.Close() CustomersByCityCommand.Connection.Close() ResultsTextBox.Text = results.ToString // C# // Set the parameters value to the // text in the CityTextBox CityParameter.Value = CityTextBox.Text; // Create a StringBuilder to store the results of the query System.Text.StringBuilder results =new System.Text.StringBuilder(); // You must open the connection before executing the command CustomersByCityCommand.Connection.Open(); // Assign the results of the SQL statement to a data reader SqlDataReader reader = CustomersByCityCommand.ExecuteReader(); while (reader.Read()) { for (int i=0; i< reader.FieldCount; i++) { results.Append(reader[i].ToString() + "\t"); } results.Append(Environment.NewLine); } // Close the data reader and the connection reader.Close(); CustomersByCityCommand.Connection.Close(); ResultsTextBox.Text = results.ToString(); 11. Run the application and click the Execute SQL button. As shown in Figure 6-4, the application displays the command results. 280 Chapter 6 Working with Data in a Connected Environment Figure 6-4 Form displaying data after executing the parameterized SQL statement 12. Type Madrid and rerun the query (click the Execute SQL button). 13. Verify that the results show only customers from the City value passed in to the parameter. � Exercise 2: Creating and Executing a Parameterized Stored Procedure 1. Create a new Windows application and name it ParameterizedStoredProcedure. 2. Add a TextBox to the form and set the following properties: ❑ Name = CategoryNameTextBox ❑ Text = Beverages 3. Add a second TextBox and set the following properties: ❑ Name = OrdYearTextBox ❑ Text = 1997 4. Add a third TextBox and set the following properties: ❑ Name = ResultsTextBox ❑ MultiLine = True ❑ ScrollBars = Both 5. Add a button and set the following properties. The form should now resemble Figure 6-5: ❑ Name = ExecuteStoredProcedureButton ❑ Text = Execute Stored Procedure Lesson 2: Working with Parameters in SQL Commands 281 Figure 6-5 Form with controls in preparation for executing the parameterized stored procedure 6. Double-click the Execute Stored Procedure button to create the button-click event handler and switch the form to code view. 7. Add references to the System.Data and System.Data.SqlClient namespaces. 8. Add code to create a connection on the form. At this point, your form code should look like the following (substitute a valid connection string for the NorthwindConnection): ' VB Imports System.Data Imports System.Data.SqlClient Public Class Form1 Private NorthwindConnection As New SqlConnection _ ("Data Source=<ValidServerName>;Initial Catalog=Northwind;Integrated Security=True") Private Sub ExecuteStoredProcedureButton_Click _ (ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles ExecuteStoredProcedureButton.Click End Sub End Class // C# using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; 282 Chapter 6 Working with Data in a Connected Environment using System.Data.SqlClient; namespace ParameterizedStoredProcedureCS { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private SqlConnection NorthwindConnection = new SqlConnection ("Data Source=<ValidServerName>;Initial Catalog=Northwind;" + "Integrated Security=True"); private void ExecuteStoredProcedureButton_Click(object sender, EventArgs e) { } } } 9. Add the following code to the ExecuteStoredProcedureButton_Click method to cre- ate a new Command object and set it to the SalesByCategory stored procedure: ' VB ' Create a new Command object Dim SalesByCategoryCommand As New SqlCommand ' Set the command properties SalesByCategoryCommand.Connection = NorthwindConnection SalesByCategoryCommand.CommandType = CommandType.StoredProcedure SalesByCategoryCommand.CommandText = "SalesByCategory" // C# // Create a new Command object SqlCommand SalesByCategoryCommand = new SqlCommand(); // Set the command properties SalesByCategoryCommand.Connection = NorthwindConnection; SalesByCategoryCommand.CommandType = CommandType.StoredProcedure; SalesByCategoryCommand.CommandText = "SalesByCategory"; 10. This stored procedure takes two parameters, so add the following code below the previous code to create the parameters and assign them to the command: ' VB ' Create the @CategoryName parameter Dim CategoryNameParameter As New SqlParameter ' Set its name and data type CategoryNameParameter.ParameterName = "@CategoryName" CategoryNameParameter.SqlDbType = SqlDbType.NVarChar Lesson 2: Working with Parameters in SQL Commands 283 ' Create the OrdYear parameter Dim OrdYearParameter As New SqlParameter("@OrdYear", SqlDbType.NVarChar) ' Add the parameters to the Commmand object SalesByCategoryCommand.Parameters.Add(CategoryNameParameter) SalesByCategoryCommand.Parameters.Add(OrdYearParameter) // C# // Create the @CategoryName parameter SqlParameter CategoryNameParameter = new SqlParameter(); // Set its name and data type CategoryNameParameter.ParameterName = "@CategoryName"; CategoryNameParameter.SqlDbType = SqlDbType.NVarChar; // Create the OrdYear parameter SqlParameter OrdYearParameter =new SqlParameter("@OrdYear", SqlDbType.NVarChar); // Add the parameters to the Commmand object SalesByCategoryCommand.Parameters.Add(CategoryNameParameter); SalesByCategoryCommand.Parameters.Add(OrdYearParameter); 11. Now add the code that will set the value of the parameters to whatever is typed into the two text boxes, set the code to run the query, and display the results in the ResultsTextBox. ' VB ' Set the parameter values to the ' text in the CategoryNameTextBox ' and the OrdYearTextBox CategoryNameParameter.Value = CategoryNameTextBox.Text OrdYearParameter.Value = OrdYearTextBox.Text ' Create a StringBuilder to store the results of the query Dim results As New System.Text.StringBuilder ' Open the connection before executing the command SalesByCategoryCommand.Connection.Open() ' Assign the results of the SQL statement to a data reader Dim reader As SqlDataReader = SalesByCategoryCommand.ExecuteReader While reader.Read For i As Integer = 0 To reader.FieldCount - 1 results.Append(reader(i).ToString & vbTab) Next results.Append(Environment.NewLine) End While ' Close the data reader and the connection reader.Close() SalesByCategoryCommand.Connection.Close() 284 Chapter 6 Working with Data in a Connected Environment ResultsTextBox.Text = results.ToString // C# // Set the parameter values to the // text in the CategoryNameTextBox // and the OrdYearTextBox CategoryNameParameter.Value = CategoryNameTextBox.Text; OrdYearParameter.Value = OrdYearTextBox.Text; // Create a StringBuilder to store the results of the query System.Text.StringBuilder results = new System.Text.StringBuilder(); // Open the connection before executing the command SalesByCategoryCommand.Connection.Open(); // Assign the results of the SQL statement to a data reader SqlDataReader reader = SalesByCategoryCommand.ExecuteReader(); while (reader.Read()) { for(int i = 0; i< reader.FieldCount; i++) { results.Append(reader[i].ToString() + "\t"); } results.Append(Environment.NewLine); } // Close the data reader and the connection reader.Close(); SalesByCategoryCommand.Connection.Close(); ResultsTextBox.Text = results.ToString(); 12. Run the application and click the Execute Stored Procedure button (see Figure 6-6). Figure 6-6 Form displaying data after executing the parameterized stored procedure [...]... Dim SaveDocCommand As New SqlCommand SaveDocCommand.Connection = NorthwindConnection SaveDocCommand.CommandText = "INSERT INTO DocumentStorage" & _ "(FileName, DocumentFile)" & _ "VALUES (@FileName, @DocumentFile)" ' Create parameters to store the filename and BLOB data Dim FileNameParameter As New SqlParameter("@FileName", SqlDbType.NChar) Dim DocumentFileParameter As New SqlParameter("@DocumentFile",... value SqlCommand SaveDocCommand = new SqlCommand(); SaveDocCommand.Connection = NorthwindConnection; SaveDocCommand.CommandText = "INSERT INTO DocumentStorage" + "(FileName, DocumentFile)" + "VALUES (@FileName, @DocumentFile)"; // Create parameters to store the filename and BLOB data SqlParameter FileNameParameter = new SqlParameter("@FileName", SqlDbType.NChar); SqlParameter DocumentFileParameter... SqlParameter _ ("@DocumentFile", SqlDbType.Binary); SaveDocCommand.Parameters.Add(FileNameParameter); SaveDocCommand.Parameters.Add(DocumentFileParameter); // Parse the filename out of the complete path // and assign it to the parameter FileNameParameter.Value = CompleteFilePath.Substring _ (CompleteFilePath.LastIndexOf("\\")+ 1); // Set the DocumentFile parameteter to the BLOB Value DocumentFileParameter.Value... SqlParameter("@DocumentFile", SqlDbType.Binary) SaveDocCommand.Parameters.Add(FileNameParameter) SaveDocCommand.Parameters.Add(DocumentFileParameter) ' Parse the filename out of the complete path ' and assign it to the parameter FileNameParameter.Value = _ CompleteFilePath.Substring(CompleteFilePath.LastIndexOf("\") + 1) ' Set the DocumentFile parameteter to the BLOB Value DocumentFileParameter.Value = BLOB ' Execute... NorthwindConnection; CreateTableCommand.CommandType = CommandType.Text; CreateTableCommand.CommandText = "IF OBJECT_ID ( 'DocumentStorage' ) IS NOT NULL " + "DROP TABLE DocumentStorage; " + "CREATE TABLE DocumentStorage(" + "DocumentID int IDENTITY(1,1) NOT NULL, " + "FileName nvarchar(255) NOT NULL, " + "DocumentFile varbinary(max) NOT NULL)"; CreateTableCommand.Connection.Open(); CreateTableCommand.ExecuteNonQuery();... Chapter 6 Working with Data in a Connected Environment CreateTableCommand.CommandText = "IF OBJECT_ID ( 'DocumentStorage' ) IS NOT NULL " & _ "DROP TABLE DocumentStorage; " & _ "CREATE TABLE DocumentStorage(" & _ "DocumentID int IDENTITY(1,1) NOT NULL, " & _ "FileName nvarchar(255) NOT NULL, " & _ "DocumentFile varbinary(max) NOT NULL)" CreateTableCommand.Connection.Open() CreateTableCommand.ExecuteNonQuery()... DialogResult = MessageBox.Show("Create the Document Storage Table?" & _ Environment.NewLine & "Click Yes to create a new DocumentStorage table Click No if you already have one!", _ "Create DocumentStorage table", MessageBoxButtons.YesNo, _ MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) Select Case response Case Is = Windows.Forms.DialogResult.Yes CreateDocumentStorageTable() Case Is = Windows.Forms.DialogResult.No... DialogResult response = MessageBox.Show("Create the Document Storage Table?" + Environment.NewLine + "Click Yes to create a new DocumentStorage table." + "Click No if you already have one!", "Create DocumentStorage table", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); switch (response) { case DialogResult.Yes: CreateDocumentStorageTable(); break; case DialogResult.No:... the BLOB to GetSavePath() ' Create the Command object to fetch the selected BLOB Dim GetBlobCommand As New SqlCommand("SELECT FileName, DocumentFile " & _ "FROM DocumentStorage " & _ "WHERE FileName = @DocName", NorthwindConnection) GetBlobCommand.Parameters.Add("@DocName", SqlDbType.NVarChar).Value = _ BlobList.Text ' Current index to write the bytes to Dim CurrentIndex As Long = 0 ' number of bytes... Database 301 GetSavePath(); // Create the Command object to fetch the selected BLOB SqlCommand GetBlobCommand = new SqlCommand("SELECT FileName, DocumentFile " + "FROM DocumentStorage " + "WHERE FileName = @DocName", NorthwindConnection); GetBlobCommand.Parameters.Add("@DocName", SqlDbType.NVarChar).Value = BlobList.Text; // Current index to write the bytes to long CurrentIndex = 0; // number of bytes to . application and name it InputOutputParameters. 2. Add a TextBox to the form and set the following properties: ❑ Name = OrderIDTextBox ❑ Text = 1 02 5 0 3. Add a second TextBox and set its Name property. FreightCostParameter.Value.ToString(); 12. Run the application and click the Get Freight Cost button. The Freight Cost TextBox displays 65.83, the cost of freight for order number 1 02 5 0. Type other valid OrderID. OBJECT_ID ( 'DocumentStorage' ) IS NOT NULL " & _ "DROP TABLE DocumentStorage; " & _ "CREATE TABLE DocumentStorage(" & _ "DocumentID int

Ngày đăng: 07/07/2014, 05:20

Tài liệu cùng người dùng

Tài liệu liên quan