1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft ADO .NET 4 Step by Step - p 19 pps

10 281 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 629,99 KB

Nội dung

156 Microsoft ADO.NET 4 Step by Step As with nonparameterized queries, this enhanced statement gets wrapped up in a SqlCommand object: C# string sqlText = @"UPDATE Employee SET Salary = @NewSalary WHERE ID = @EmployeeID"; SqlCommand salaryUpdate = new SqlCommand(sqlText, linkToDB); Visual Basic Dim sqlText As String = "UPDATE Employee SET Salary = @NewSalary WHERE ID = @EmployeeID" Dim salaryUpdate = New SqlCommand(sqlText, linkToDB) The SqlCommand class includes a Parameters collection to which you add the specific re- placement values for each placeholder. You wrap up each parameter in an instance of SqlParameter, setting its properties as needed, and adding it to the SqlCommand.Parameters collection. When you execute the command, ADO.NET passes both the placeholder-laden SQL text and the parameter collection to the database for evaluation. Each parameter includes the elements you would expect: the parameter name (which must match a placeholder name in the SQL statement), the data type along with any data type- specific settings (such as the length of string parameters), the actual data content to be included in the processed command, and a few other generic settings. To add a parameter to a command, create a SqlParameter instance and add it to the SqlCommand object. C# SqlParameter paramValue = new SqlParameter("@NewSalary", SqlDbType.Money); paramValue.Value = 50000m; salaryUpdate.Parameters.Add(paramValue); paramValue = new SqlParameter("@EmployeeID", SqlDbType.BigInt); paramValue.Value = 25L; salaryUpdate.Parameters.Add(paramValue); Visual Basic Dim paramValue As New SqlParameter("@NewSalary", SqlDbType.Money) paramValue.Value = 50000@ salaryUpdate.Parameters.Add(paramValue) paramValue = New SqlParameter("@EmployeeID", SqlDbType.BigInt) paramValue.Value = 25& salaryUpdate.Parameters.Add(paramValue) Chapter 10 Adding Standards to Queries 157 SqlParameter includes lots of constructor options for setting the data type of the passed data, plus other settings. Or you can go the traditional route and update the object’s indi- vidual properties directly, including the following:  ParameterName The name of the parameter; that is, the placeholder. Don’t forget to include the @ sign at the start of the name.  DbType or SqlDbType One of the System.Data.SqlDbType enumeration values, which all parallel the available data types in SQL Server. For example, SqlDbType.VarChar maps to SQL Server’s varchar column type. Both DbType and SqlDbType refer to the same property; update either one as needed.  IsNullable Indicates whether the parameter accepts NULL values.  Precision and Scale Some of SQL Server’s numeric data types require specific preci- sion and scale values. Use these properties to configure the data from ADO.NET’s point of view.  Size Similar to Precision and Scale, Size is commonly used for text and binary data types. It affects only the amount of data sent to SQL Server with a query. If your query sends data back through a parameter (described below), it ignores this Size setting.  Value and SqlValue The actual value that will replace the placeholder in the SQL statement. Use Value to work with data defined using the standard .NET data types. Use the SqlValue property instead to work with data in a format that more closely re- sembles SQL Server’s data types, and as expressed through the classes in the System. Data.SqlTypes namespace. If your data needs are simple, you can let the SqlCommand.Parameters collection define the data type of your parameters for you. The collection’s AddWithValue method accepts the parameter name and the intended value and adds a new SqlParameter instance to the com- mand using the specified settings. C# salaryUpdate.Parameters.AddWithValue("@NewSalary", 50000m); salaryUpdate.Parameters.AddWithValue("@EmployeeID", 25L); Visual Basic salaryUpdate.Parameters.AddWithValue("@NewSalary", 50000@) salaryUpdate.Parameters.AddWithValue("@EmployeeID", 25&) Once the parameters are all in place, calling one of the command’s Execute methods processes the command on the database, and returns any results as with nonparameterized queries. 158 Microsoft ADO.NET 4 Step by Step C# salaryUpdate.ExecuteNonQuery(); Visual Basic salaryUpdate.ExecuteNonQuery() Updating Data with Parameters: C# 1. Open the “Chapter 10 CSharp” project from the installed samples folder. The project includes multiple Windows.Forms classes and a sealed class named General. 2. Open the code for the General class. This class centralizes much of the database func- tionality for the sample application. Locate the GetConnectionString function, a routine that uses a SqlConnectionStringBuilder to create a valid connection string to the sample database. It currently includes the following statements: builder.DataSource = @"(local)\SQLExpress"; builder.InitialCatalog = "StepSample"; builder.IntegratedSecurity = true; Adjust these statements as needed to provide access to your own test database. 3. Open the code for the RenameCustomer form. This form lets the user modify the FullName value for a single record in the Customer database table. Locate the ActOK_ Click event handler. This routine does the actual update of the record. Just after the “Save the new name” comment, add the following code: sqlText = "UPDATE Customer SET FullName = @NewName WHERE ID = @CustID"; commandWrapper = new SqlCommand(sqlText); commandWrapper.Parameters.AddWithValue("@NewName", NewName.Text.Trim()); commandWrapper.Parameters.AddWithValue("@CustID", ActiveCustomerID); try { General.ExecuteSQL(commandWrapper); } catch (Exception ex) { MessageBox.Show("Error occurred updating customer name: " + ex.Message); return; } These statements create a SqlCommand object with a SQL statement that includes two placeholders: @NewName and @CustID. The code then adds two matching parameters to the command and sends it to the database for processing. 4. Run the program. On the Customer Management form, select a customer from the list of customers and then click Rename Customer. When the Rename Customer form ap- pears, enter a new value in the New Name field and then click OK. This process updates the database using the newly added code. Chapter 10 Adding Standards to Queries 159 Updating Data with Parameters: Visual Basic 1. Open the “Chapter 10 VB” project from the installed samples folder. The project in- cludes multiple Windows.Forms classes and a module named General. 2. Open the code for the General module. This file centralizes much of the database func- tionality for the sample application. Locate the GetConnectionString function, a routine that uses a SqlConnectionStringBuilder to create a valid connection string to the sample database. It currently includes the following statements: builder.DataSource = "(local)\SQLExpress" builder.InitialCatalog = "StepSample" builder.IntegratedSecurity = True Adjust these statements as needed to provide access to your own test database. 3. Open the code for the Rena meCustomer form. This form lets the user modify the FullName value for a single record in the Customer database table. Locate the ActOK_ Click event handler. This routine does the actual update of the record. Just after the “Save the new name” comment, add the following code: sqlText = "UPDATE Customer SET FullName = @NewName WHERE ID = @CustID" commandWrapper = New SqlCommand(sqlText) commandWrapper.Parameters.AddWithValue("@NewName", NewName.Text.Trim) commandWrapper.Parameters.AddWithValue("@CustID", ActiveCustomerID) Try ExecuteSQL(commandWrapper) Catch ex As Exception MessageBox.Show("Error occurred updating customer name: " & ex.Message) Return End Try These statements create a SqlComman d object with a SQL statement that includes two placeholders: @NewName and @CustID. The code then adds two matching parameters to the command and sends it to the database for processing. 160 Microsoft ADO.NET 4 Step by Step 4. Run the program. On the Customer Management form, select a customer from the list of customers and then click Rename Customer. When the Rename Customer form ap- pears, enter a new value in the New Name field and then click OK. This process updates the database using the newly added code. Using Parameters with Other Providers The OLE DB and ODBC providers also include support for parameterized queries. However, the definitions of both the command text and the associated parameters vary somewhat from the SQL Server implementation. Instead of including placeholder names prefixed with @ signs, each replaceable element appears as a nameless question mark (?) in the command text. Parameters added to the associated OleDbCommand or OdbcCommand instance must be added in the order indicated by the placeholders. Although the command text does not include parameter names, each added OleDbParameter or OdbcParameter instance should still include @-prefixed names. C# string sqlText = @"UPDATE Employee SET Salary = ? WHERE ID = ?"; SqlCommand salaryUpdate = new SqlCommand(sqlText, linkToDB); salaryUpdate.Parameters.AddWithValue("@NewSalary", 50000m); salaryUpdate.Parameters.AddWithValue("@EmployeeID", 25L); Visual Basic Dim sqlText As String = "UPDATE Employee SET Salary = ? WHERE ID = ?" Dim salaryUpdate = New SqlCommand(sqlText, linkToDB) salaryUpdate.Parameters.AddWithValue("@NewSalary", 50000@) salaryUpdate.Parameters.AddWithValue("@EmployeeID", 25&) Chapter 10 Adding Standards to Queries 161 Using Parameters in Stored Procedures Calls to stored procedures with parameterized queries vary only slightly from those to standard statements. There are four main differences you need to consider when access- ing stored procedures. The first is simple: Make sure you set the SqlCommand object’s CommandType property to CommandType.StoredProcedure. The second difference is equally simple: The command object’s Comman dText property should include only the name of the stored procedure. Exclude any arguments or query elements. The third difference is in how you name the parameters. As with standard queries, each parameter includes an @-prefixed name and a data type, plus other optional settings you might want to configure. Unlike standard queries, you have no flexibility in how you define the parameter names. They must match precisely the parameter names used when the stored procedure was defined within SQL Server. The last difference has to do with the direction of a parameter. The SqlParam eter class in- cludes a D irection property that tells ADO.NET which way data flows from your query’s data value to the stored procedure. There are four available System.Data.ParameterDirection options:  ParameterDirection.Input The parameter value is considered input, flowing from the application to the stored procedure. This is the default for all parameters.  ParameterDirection.Output The parameter is used to retrieve data back from the stored procedure, much like a ByRef (Visual Basic) or out (C#) function argument.  ParameterDirection.InputOutput A combination of the input and output directions. Your application provides an input value that can be modified and returned by the stored procedure.  ParameterDirection.Retu rnValue For stored procedures or other database features that sport a return value, this parameter type lets you collect that value. Parameters added to standard query commands also support the Direction property, but in most cases the default of ParameterDirection.Input is the right choice. The following SQL Server stored procedure includes an input value (@locationName), an out- put value (@newID), and a return value (@@ROW COUNT): CREATE PROCEDURE AddLocation (@locationName varchar(50), @newID bigint OUT) AS BEGIN INSERT INTO BuildingLocation (Name) VALUES (@locationName); SET @newID = SCOPE_IDENTITY(); RETURN @@ROWCOUNT; END 162 Microsoft ADO.NET 4 Step by Step The following code calls the AddL ocation stored procedure, passing it the name of a new lo- cation and returning the new ID value: C# // Use a stored procedure to add a new building location. string sqlText = "dbo.AddLocation"; SqlCommand locationCommand = new SqlCommand(sqlText, linkToDB); locationCommand.CommandType = CommandType.StoredProcedure; // Add the input parameter: locationName. SqlParameter workParameter = locationCommand.Parameters.AddWithValue( "@locationName", LocationNameField.Text.Trim()); workParameter.Size = 50; // Add the output parameter: newID. workParameter = locationCommand.Parameters.Add("@newID", SqlDbType.BigInt); workParameter.Direction = ParameterDirection.Output; // Add the return value parameter. The name is not important. workParameter = locationCommand.Parameters.Add("@returnValue", SqlDbType.Int); workParameter.Direction = ParameterDirection.ReturnValue; // Add the location. locationCommand.ExecuteNonQuery(); // Access returned values as: // locationCommand.Parameters["@newID"].Value // locationCommand.Parameters["@returnValue"].Value Visual Basic ' Use a stored procedure to add a new building location. Dim sqlText As String = "dbo.AddLocation" Dim locationCommand As New SqlCommand(sqlText, linkToDB) locationCommand.CommandType = CommandType.StoredProcedure ' Add the input parameter: locationName. Dim workParameter As SqlParameter = locationCommand.Parameters.AddWithValue( "@locationName", LocationNameField.Text.Trim) workParameter.Size = 50 Chapter 10 Adding Standards to Queries 163 ' Add the output parameter: newID. workParameter = locationCommand.Parameters.Add("@newID", SqlDbType.BigInt) workParameter.Direction = ParameterDirection.Output ' Add the return value parameter. The name is not important. workParameter = locationCommand.Parameters.Add("@returnValue", SqlDbType.Int) workParameter.Direction = ParameterDirection.ReturnValue ' Add the location. locationCommand.ExecuteNonQuery() ' Access returned values as: ' locationCommand.Parameters("@newID").Value ' locationCommand.Parameters("@returnValue").Value The return value will be 1 if the code was successful, or 0 if the insert failed (along with a thrown error). Calling a Stored Procedure with Parameters: C# Note This exercise uses the “Chapter 10 CSharp” sample project and continues from where the previous exercise in this chapter left off. 1. Open the code for the ViewOrders form. This form processes data from a stored proce- dure that returns two distinct sets of records. The stored procedure GetCustomerOrders has the following definition: CREATE PROCEDURE dbo.GetCustomerOrders(@customerID bigint) AS BEGIN SELECT * FROM Customer WHERE ID = @customerID; SELECT * FROM OrderEntry WHERE Customer = @customerID ORDER BY OrderDate; END; 2. Locate the ViewOrders_Load event handler. This routine calls the stored procedure and processes the returned records. In the try block, just after the “Process the query ” comment, add the following statements: sqlText = "dbo.GetCustomerOrders"; commandWrapper = new SqlCommand(sqlText, linkToDB); commandWrapper.CommandType = CommandType.StoredProcedure; commandWrapper.Parameters.AddWithValue("@customerID", ActiveCustomerID); customerReader = commandWrapper.ExecuteReader(); 164 Microsoft ADO.NET 4 Step by Step These lines add the @customerID parameter to the stored procedure command. The @customerID parameter name must match the @customerID parameter as defined in the original stored procedure. 3. Just after the “First read the customer record” comment, add the following code: customerReader.Read(); CustomerName.Text = (string)customerReader["FullName"]; AnnualFee.Text = string.Format("{0:c}", (decimal)customerReader["AnnualFee"]); These statements process the first set of results from the stored procedure, the SELECT statement for the Customer table. 4. Just after the “Read the next set, which contains the orders” comment, add the follow- ing code: customerReader.NextResult(); while (customerReader.Read()) { oneOrder = new OrderInfo(); oneOrder.ID = (long)customerReader["ID"]; oneOrder.OrderDate = (DateTime)customerReader["OrderDate"]; oneOrder.OrderTotal = (decimal)customerReader["Total"]; AllOrders.Items.Add(oneOrder); } This code accesses the records in the second set of results, the SELECT statement for the OrderEntry table, via the NextResult method call. 5. Run the program. On the Customer Management form, select a customer from the list of customers and then click View Orders. When the View Orders form appears, it in- cludes content from both SELECT statements as returned by the stored procedure. Chapter 10 Adding Standards to Queries 165 Calling a Stored Procedure with Parameters: Visual Basic Note This exercise uses the “Chapter 10 VB” sample project and continues from where the pre- vious exercise in this chapter left off. 1. Open the code for the ViewOrders form. This form processes data from a stored proce- dure that returns two distinct sets of records. The stored procedure GetCustomerOrders has the following definition: CREATE PROCEDURE dbo.GetCustomerOrders(@customerID bigint) AS BEGIN SELECT * FROM Customer WHERE ID = @customerID; SELECT * FROM OrderEntry WHERE Customer = @customerID ORDER BY OrderDate; END; 2. Locate the ViewOrders_Load event handler. This routine calls the stored procedure and processes the returned records. In the Try block, just after the “Process the query ” comment, add the following statements: sqlText = "dbo.GetCustomerOrders" commandWrapper = New SqlCommand(sqlText, linkToDB) commandWrapper.CommandType = CommandType.StoredProcedure commandWrapper.Parameters.AddWithValue("@customerID", ActiveCustomerID) customerReader = commandWrapper.ExecuteReader() These lines add the @customerID parameter to the stored procedure command. The @customerID parameter name must match the @customerID parameter as defined in the original stored procedure. 3. Just after the “First read the customer record” comment, add the following code: customerReader.Read() CustomerName.Text = CStr(customerReader!FullName) AnnualFee.Text = Format(CDec(customerReader!AnnualFee), "Currency") These statements process the first set of results from the stored procedure, the SELECT statement for the Customer table. . nonparameterized queries. 158 Microsoft ADO. NET 4 Step by Step C# salaryUpdate.ExecuteNonQuery(); Visual Basic salaryUpdate.ExecuteNonQuery() Updating Data with Parameters: C# 1. Open the “Chapter. 156 Microsoft ADO. NET 4 Step by Step As with nonparameterized queries, this enhanced statement gets wrapped up in a SqlCommand object: C# string sqlText = @"UPDATE Employee SET Salary. customerReader = commandWrapper.ExecuteReader(); 1 64 Microsoft ADO. NET 4 Step by Step These lines add the @customerID parameter to the stored procedure command. The @customerID parameter name must

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

TỪ KHÓA LIÊN QUAN