Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P9 pdf

50 417 0
Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P9 pdf

Đ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

• • End Sub • • • Private Sub Button1_Click(ByVal sender As System.Object, _ • ByVal e As System.EventArgs) Handles Button1.Click • • ’Move to first row and populate text boxes. • Session(“MyRowID”) = 0 • MoveToRow() • • End Sub • • Private Sub Button2_Click(ByVal sender As System.Object, _ • ByVal e As System.EventArgs) Handles Button2.Click • • ’Move to previous row and populate text boxes. • If Session(“MyRowID”) > 0 Then • Session(“MyRowID”) -= 1 • End If • MoveToRow() • • End Sub • • • Private Sub Button3_Click(ByVal sender As System.Object, _ • ByVal e As System.EventArgs) Handles Button3.Click • • ’Move to next row and populate text boxes. • If Session(“MyRowID”) < _ • Ds1.Tables(“Products”).Rows.Count - 1 Then • Session(“MyRowID”) += 1 • End If • MoveToRow() • • End Sub • • • Private Sub Button4_Click(ByVal sender As System.Object, _ • ByVal e As System.EventArgs) Handles Button4.Click • • ’Move to last row and populate text boxes. • Session(“MyRowID”) = Ds1.Tables(“Products”).Rows.Count - 1 • MoveToRow() • • End Sub • Creat ing Da ta base Obj ect s fr om W eb Pa ges Your applications will sometim es need the availability of custom database objects. For exam ple, stored procedures, which store precompiled, optim ized SQL code, are great for managing data manipulation tasks, such as inserting new records Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. into a table, and data definition tasks, such as dynam ically creating a new table. If you happen to create a custom table for your application, your application can probably also benefit from one or more stored procedures performing data manipulation tasks for t he table. For exam ple, your application can pass the stored procedure param eters specifying the column values for a new row, and the stored procedure can execute the I NSERT INTO statem ent. I f your application needs the value for a colum n with an Identit y property created on the SQL Server instance, the stored procedure can return it as an output param et er. The sam ple for this section dem onstrat es the creation of a table and a stored procedure. The sample is the setup program for the next section that dem onstrates how to program data manipulation tasks. Specifically, you will learn how to create a table and a stored procedure on a SQL Server instance from an ASP.NET application. Figure 11-20 shows the Web page for the sam ple. The page’s nam e is WebFrom1.aspx, and it resides in the SetupForWebUpdateSample project. The page includes two buttons and a hyperlink. The buttons have Text property settings reflecting the text they show. The button I D property settings are Button1 for t he top button and Button2 for the one below it. The hyperlink control has two design-t im e property settings. First, its Text property specifies the message to display when rendered on a Web page. Second, the Navigat eUrl property designates the URL of t he page to which to pass control when a user clicks the hyperlink. If you are running the application against another Web server besides t he local one on your workstation, you will need to update t he Navigat eUrl property for the hyperlink control. Figure 1 1 - 2 0 . W ebForm 1 .a spx in t h e Set upFor W ebUpdat eSa m ple p roj ect . The sam ple’s new table is essent ially a scratch copy of the Shippers table in the Northwind database. By creating a scratch copy of the table, you will be able to make changes against the new sam ple table without destroying the original data in the sample database. The But t on1_Click event procedure perform s three subtasks as it creates a new table named ASPNETShippers. First it rem oves the ASPNETShippers table if it already exists in the database. Next it creates the ASPNETShippers table. Third it populates the rows of the ASPNETShippers table with rows from the Shippers table. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The listing that follows starts by declaring and instantiating a SqlConnect ion object (cnn1) and a SqlCom m and object (cm d1 ). By declaring the objects at the module level, I can use them in event procedures for each button in Figure 11- 20. The Button1_Click event procedure starts by specifying the connection string for cnn1 and opening the object. Next the procedure assigns cnn1 to the Connection property for cm d1, the SqlCom m and obj ect. After these prelim inary steps, the procedure successively repeats two statem ents for assigning a Com m andText property to cm d1 and then invoking t he ExecuteNonQuery m ethod for cm d1. Apply the Execut eNonQuery m et hod of a SqlCom m and object when the object’s Com m andText property doesn’t return a result set. The three Com m andText property settings rem ove any prior version of the ASPNETShippers table, create a new ASPNETShippers table, and populate the ASPNETShippers table with rows from t he Shippers table in the Northwind database. The But t on1_Click event procedure concludes by closing cnn1. The logic for the Button2_Click event procedure follows the same basic design as that in the Button1_Click event procedure. The overall process is: (1) m ake a connection, (2) run one or m ore SQL statem ent s with a SqlCom m and object, and (3) close the connection. The objective of the But t on2_Click event procedure is to create a new stored procedure nam ed udpI nsertANewASPNETShipper. The event procedure execut es two SQL statements to achieve this objective. First it runs one statem ent to remove any prior version of the connection in the Northwind database. Second it runs a procedure t o create a new version of the udpI nsertANewASPNETShipper stored procedure. We discussed the logic for this stored procedure in Chapter 10. That chapter demonstrated how to create the stored procedure in Query Analyzer and discussed the logic that the SQL statements express. This chapter extends the earlier treatm ent of the topic by dem onstrating how to create t he stored procedure program matically from within ASP.NET. N ot e For data definition SQL statements to function properly, such as those in the But ton1_Click and Button2_Click event procedures, you must run them from a login with appropriate permission to create database objects on the SQL Server instance to which you connect. See Chapter 7 for detailed coverage of SQL Server security, including logins and permissions. Alternatively, you can use the SQL Server sa login. However, this is poor application design because it allows users unrestricted authority on a SQL Server. Dim cnn1 As New SqlClient.SqlConnection()Dim cmd1 As New SqlClient.Sq lCommand() Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ’Make connection to northwind database. cnn1.ConnectionString = “Data Source=(local);” & _ “Initial Catalog=northwind;” & _ “Integrated Security=SSPI" cnn1.Open() ’Assign connection to cmd1. cmd1.Connection = cnn1 ’Execute query to drop prior version of table. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. cmd1.CommandText = “IF EXISTS (“ & _ “SELECT * FROM INFORMATION_SCHEMA.TABLES “ & _ “WHERE TABLE_NAME = ’ASPNETShippers’) “ & _ “DROP TABLE dbo.ASPNETShippers" cmd1.ExecuteNonQuery() ’Execute query to create new version of table. cmd1.CommandText = “CREATE TABLE dbo.ASPNETShippers “ & _ “(“ & _ “ShipperID int IDENTITY (1, 1) NOT NULL, “ & _ “CompanyName nvarchar (40) NOT NULL, “ & _ “Phone nvarchar (24) NULL, “ & _ “CONSTRAINT PK_ASPNETShippers “ & _ “PRIMARY KEY CLUSTERED (ShipperID)” & _ “)" cmd1.ExecuteNonQuery() ’Populate table based on Shippers. cmd1.CommandText = _ “SET IDENTITY_INSERT dbo.ASPNETShippers ON “ & _ “INSERT INTO ASPNETShippers “ & _ “(ShipperID, CompanyName, Phone) “ & _ “SELECT * FROM Shippers “ & _ “SET IDENTITY_INSERT dbo.ASPNETShippers OFF" cmd1.ExecuteNonQuery() cnn1.Close() End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click ’Make connection to northwind database. cnn1.ConnectionString = “Data Source=(local);” & _ “Initial Catalog=northwind;” & _ “Integrated Security=SSPI" cnn1.Open() ’Assign connection to cmd1. cmd1.Connection = cnn1 ’Drop any prior version of udpInsertANewASPNETShipper. cmd1.CommandText = “IF EXISTS (“ & _ “SELECT ROUTINE_NAME “ & _ “FROM INFORMATION_SCHEMA.ROUTINES “ & _ “WHERE ROUTINE_TYPE = ’PROCEDURE’ AND “ & _ “ROUTINE_NAME = ’udpInsertANewASPNETShipper’) “ & _ “DROP PROCEDURE dbo.udpInsertANewASPNETShipper" cmd1.ExecuteNonQuery() ’Create a new version of udpInsertANewASPNETShipper. cmd1.CommandText = _ “CREATE PROCEDURE udpInsertANewASPNETShipper “ & _ “@CompanyName nchar(40), “ & _ “@Phone nvarchar (24), “ & _ “@Identity int OUT “ & _ “AS “ & _ “INSERT INTO ASPNETShippers “ & _ “(CompanyName, Phone) “ & _ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. “VALUES(@CompanyName, @Phone) “ & _ “SET @Identity = SCOPE_IDENTITY()" cmd1.ExecuteNonQuery() cnn1.Close() End Sub Dat a Manipulat ion from ASP.N ET After running the application in t he preceding section, you will have a new copy of the ASPNETShippers table in the Northwind database as well as a stored procedure, udpI nsert ANew ASPNETShipper, to facilitate inserting new rows into the ASPNETShippers table. The sample application in this section illustrates how to m odify, insert, and delet e rows in the ASPNETShippers table from an ASP.NET application. The application builds on the browsing sample illustrated by the WebForm 1.aspx page in the NavTextBoxes proj ect. The addition of data manipulation to that earlier application is particularly interesting because that application used an unbound form to display colum n values from the Shippers table. I n other words, the form field values don’t bind t o any data source. Therefore, all data manipulation tasks must be performed in code. The sam ple in this section is im portant for another reason. The application enables users to update a SQL Server database over the Web. N ot e As with the sample in the preceding section, users of this application must have permission to perform a task before the application autom ating that task will work. In this section, the tasks are the classic three data manipulation ones of m odifying, inserting, and deleting records. W e b Page Layou t a nd Opera t ion Figure 11-21 shows the Web page layout for this application. The page’s name is WebForm 1.aspx in the UpdateWithWebForm project. Except for four new buttons at the bottom of the page, the page layout looks similar to the one in Figure 11- 18 for browsing records with text box controls. The four new buttons facilitate changes to the row currently appearing on t he Web page, delete the row currently appearing, and clear t he fields and insert a new row int o the database based on new form field values. The Web page in Figure 11-21 connects to the ASPNETShippers, instead of the Shippers, table in the Northwind database. This distinction enables application users of the sam ple in this section to m anipulate the data appearing on the Web page without changing the original data in the sample database. By contrasting the Design views of the two pages, you will also notice that the new Web page has no ADO.NET objects created at design tim e. You can tell t his because the system tray doesn’t appear in Figure 11-21. Figure 1 1 - 2 1 . W ebForm 1 .a spx in t h e Upda t eW ithW ebForm proj ect . Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The entire reason for this sample is to dem onstrate that you can enable data manipulation tasks from a Web page with ASP.NET. Figure 11-22 starts to dem onstrate this capability by showing two views of the Web page in operation. The top window shows the Web page aft er a click of the Clear button (its name is cm dClear) and then the addition of new text in two of the text boxes. The cm dClear button clears the form on the Web page so the user can enter a new row of data. I n this top window, you can see that the Com panyNam e and Phone values for a new shipper have been entered but that the top text box for ShipperI D is em pty. That’s because the SQL Server instance assigns a value to this field. Clicking the I nsert button (its nam e is cm dI nsert) changes the browser to look like the window in the bottom port ion of Figure 11-22. Notice that the Com panyNam e and Phone text boxes are the sam e. However, you now have a ShipperID text box value. SQL Server generated this value on the server, and the UpdateWithWebForm application retrieved the value by capturing the return parameter value from the udpInsertANewASPNETShipper stored procedure. Figure 1 1 - 2 2 . W ebForm 1 .a spx in t h e Upda t eW ith W ebForm proj ect before and aft er com m itting an in sert t o the ASPN ETSh ippe rs t a ble. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 11-23 shows the row entered in the preceding sample in the process of being m odified. Notice that the user changed the last digit in the telephone num ber from 7 to 8. The application doesn’t comm it this change until the user clicks the Modify button. (I ts nam e is cm dModify.) After the user clicks cm dModify, the application conveys the new value to the SQL Server instance and refreshes the local copy of the data set on t he Web page with the table of values from the SQL Server instance. Figure 1 1 - 2 3 . W ebForm 1 .a spx in t h e Upda t e W ithW ebForm project j u st befor e a m od ifica t ion t o the t eleph on e n um be r for t he r ow adde d in Figure 1 1 - 2 2 . Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 11-24 shows the Delete button (its name is cm dDelet e) in operation. I n the top window, you can see the new row with its edited Phone value. The cursor rests on the cm dDelet e button. Clicking this button removes the row appearing on the Web page from the ASPNETShippers table in the SQL Server instance and updates the data set on the Web page to reflect this result. Because the click to the cm dDelet e button rem oved the former last row in the Shippers data set, the Web page shows the new last row with a ShipperID column value of 3. The Click event procedure behind the cm dDelet e button m anages the display of which row appears on the page after the rem oval of a row. For exam ple, if a user rem oved the first row (with a ShipperID colum n value of 1), the row appearing on the Web page would be the new first row in the data set with a ShipperID value of 2. Figure 1 1 - 2 4 . W ebForm 1 .a spx in t h e Upda t e W ithW ebForm project j u st befor e and just after t h e rem ova l of t h e row t hat h ad it s Ph on e v alu e edit ed in Figur e 1 1 - 2 3 . Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Code Be hind t h e W eb Page The code for performing data manipulation on a Web page parallels that for perform ing data manipulation in a Windows form. However, one important difference is that in a Windows form, your code has to create most of the ADO.NET obj ects, such as a SqlDat aAdapter and a data set, just once. I n the case of a Web application, your code will typically have to re-create these objects each time a Web page does a round-trip between a browser and a Web server— for exam ple, every t ime the user clicks a butt on on the Web page. As mentioned previously, you should keep the size of the data set on a Web page sm all for this reason. In our case, the ASPNETShippers table is already a sm all table of j ust three original rows. I f your original data source is large, consider pulling down just a small portion of it on successive round-trips by using a stored procedure or a user-defined function that ret urns a customizable result set based on input that you pass it through a paramet er. The following listing includes those parts of the code behind the Web page that pertain directly to the data m anipulation part of the sample. The data display and navigation code closely follow the code appearing in the section tit led “Navigating Text Boxes Through a Data Set”. In order to conserve space in this book for fresh information, I direct you to the code samples for this book, where the complete listing is available for the code behind the Web page. The listing starts by declaring and instantiating at the m odule level four ADO.NET objects: a SqlConnection object (cnn1), a SqlCom m and object (cm d1), a SqlDat aAdapter object (dap1), and a DataSet object (das1). The Page_Load event procedure uses each of these objects, and the objects find selective use in other event procedures throughout the code behind the page. After m aking a connection to the Northwind dat abase, the Page_Load event procedure declares the dap1 data adapter dependent on all the colum ns from all the rows of the ASPNETShippers table. Next the procedure defines the Updat eCom m and property for the data adapter. A SQL UPDATE statem ent with parameters specifies the items to update. After the SQL statem ent for the Updat eCom m and property, two additional statem ents add param eters to the command for the Updat eCom m and property. These param eters allow the Web page to pass values from the entries in its text boxes. The next parameter is for the text box holding a ShipperID value on the Web page. Whereas the param eter ties to the ShipperID value in the data set behind the Web page, it uses the row currently appearing in the first text box on the Web page. The next several lines of code in the Page_Load event procedure define the I nsertCom m and property for the dap1 data adapter and its associated parameters. I n this case, the procedure designates the perform ance of the insert via the udpI nsertANew ASPNETShipper stored procedure. Recall that the preceding section dem onstrated how to create this stored procedure in the code behind a separate stand-alone Web page. The statem ents adding parameters illustrate t he syntax for passing param eters to a stored procedure and capturing a return value from a stored procedure. Notice that you designate a Direct ion property for prm 2 with the Param et erDirect ion.Output enum eration value. This parameter (prm2) returns the Identit y value for the inserted row by the SQL Server instance. The next block of code in the Page_Load event procedure defines the Delet eCom m and property and its parameter for the dap1 object. This block of code uses a SQL DELETE statem ent to designate which row to drop from the ASPNETShippers table along wit h the row’s copy in the data set behind the Web page. Because the ShipperID value is the primary key of the ASPNETShippers table, t he code uniquely identifies a row to remove from the table by specifying a value for this column. After defining the dap1 data adapter and its data manipulation properties, the Page_Load event procedure perform s two more essential tasks. First the Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark I f you ar e a Visual Basic dev eloper m igrat ing... OK SQLX M L M a n a ge d Cla sse s Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark SQLXML Managed Classes enable you wr it e Visual Basic NET program s t o t ap t he feat ur es fr om t he second and t hird Web r eleases Ther e ar e t hr ee SQLXML m anaged classes Their nam es are SqlXm lCom m and, SqlXm lParam et er , and SqlXm lAdapt er You use t hese classes w it hin Visual. .. designat e t he sqloledb dat a provider as well as t he classic ADO and ADO.NET feat ur es of a serv er , dat abase, and securit y ident ificat ion For exam ple, Dim cmd1 As SqlXmlCommand = New SqlXmlCommand(provider=sqloledb; _ server= servername;database=databasename;user id=userlogin; _ password=userpassword) Befor e y ou can use ( or inst ant iat e) any SQLXML m anaged class, y our Visual Basic NET m... (“@CompanyName", SqlDbType.NVarChar, 40, _ “CompanyName”) dap1.InsertCommand.Parameters.Add _ (“@Phone", SqlDbType.NVarChar, 24, _ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark “Phone”) ’Designate an output parameter for the identity ’value assigned within SQL Server so that your ’local ASPNETShippers table can have a matching ’ShipperID column value Dim prm2 As SqlClient.SqlParameter... XMLWebSam ple This ASP.NET pr oj ect has t wo folders, one for t he wwwr oot folder w it hin t he I net pub direct or y on your Web server, and a second one for inclusion in t he norm al place where you hold y our Visual Basic NET Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark solut ion folders Bot h folders for t he ASP.NET solut ion have t he nam e XMLWebSam ple SQL Ser ve r... W e b Re le a se 3 Web Release 3 is part of t he Microsoft SQL Ser v er 2000 Web Ser vices Toolk it Web Release 3 becam e available as a st and- alone pr oduct on February 9, 2002 The t oolk it shipped slight ly lat er ( Febr uary 14, 2002) The headline capabilit y of t he Microsoft SQL Serv er 2000 Web Serv ices Toolk it is it s abilit y t o expose SQL Ser ver st ored procedures as XML Web ser v... ed t he insert Figu r e 1 1 - 2 7 W e bFor m 1 a sp x from t h e I sVa lidSa m ple pr oj e ct w it h an in va lid valu e in t h e Ph on e t ex t box Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Figu r e 1 1 - 2 8 W eb For m 1 a spx fr om t h e I sVa lid Sa m p le p roj ect a f t er it s fix Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark... s t hat you cr eat e w it h Visual Basic NET fr om a SQL Ser ver dat a source All except one of t he sam ples for t his chapt er r eside in Module1 of t he XMLSam ples solut ion These sam ples highlight t he Visual Basic NET code for m anaging XML docum ent s when w or king wit h SQL Ser ver dat a sources Ex am ine ot her chapt ers for m ore general cov erage of Visual Basic NET dev elopm ent ( For... assign a value t o a param et er at r un t im e Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark SqlX m lAd ap t e r Class SqlXm lAdapt er obj ect s serv e a purpose t hat generally corr esponds t o t hat for t he SqlDat aAdapt er obj ect in t he Syst em Dat a.SqlClient nam espace Aft er declar ing a variable as a SqlXm lAdapt er obj ect , y ou can inst ant iat e t he var iable... Web page Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark t he prev ious row before t he one j ust delet ed I f t hat row ( t he one j ust delet ed) was t he first row, t he pr ocedur e shows t he old second r ow, w hich is t he new first row Dim cnn1 As New SqlClient.SqlConnection()Dim cmd1 As New SqlClient.Sq lCommand() Dim dap1 As New SqlClient.SqlDataAdapter() Dim das1 . Figur e 1 1 - 2 3 . Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Please purchase PDF Split-Merge on www.verypdf.com to. with appropriate permission to create database objects on the SQL Server instance to which you connect. See Chapter 7 for detailed coverage of SQL Server

Ngày đăng: 21/01/2014, 08:20

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan