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

50 510 0
Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P7 ppt

Đ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

labels visible by passing the argum ent True t o ShowLabelsBoxes. As a resu lt , a user can ent er a SQL Server login and password so t hat t he form can at tem pt t o m ake a connection based on a SQL Server instead of a Windows login. Finally, by click ing the Windows NT radio but ton, the user invok es t he RadioButt on1_CheckedChanged event pr ocedure. This procedure m akes t he cont r ols for SQL Server login credent ials invisible if t hey are show ing. When t he user clicks t his RadioBut t on1, it indicat es he or she want s t o make a connection wit h a Windows login. Therefore, Form 3 doesn’t need to show t he contr ols for a SQL Server login. Private Sub Form3_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ’Set RadioButton1 to Checked for connection via ’Windows NT login. RadioButton1.Checked = True ’Hide login and password controls because they ’aren’t necessary with Windows NT login. ShowLabelsBoxes(False) End Sub Private Sub RadioButton1_CheckedChanged _ (ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles RadioButton1.CheckedChanged ’Hide login and password controls because they ’aren’t necessary with Windows NT login. ShowLabelsBoxes(False) End Sub Private Sub RadioButton2_CheckedChanged _ (ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles RadioButton2.CheckedChanged ’Show login and password controls because they ’are necessary for a SQL Server login. ShowLabelsBoxes(True) End Sub Sub ShowLabelsBoxes(ByVal bolShowEm As Boolean) ’Set the visibility of the second and third text ’boxes and their labels according to the value ’of bolShowEm. Label2.Visible = bolShowEm TextBox2.Visible = bolShowEm Label3.Visible = bolShowEm TextBox3.Visible = bolShowEm End Sub The following excerpt from t he Form 3 m odule shows the code devot ed to m aking the connect ion based on t he radio button selection and t ext box ent ries. The excerpt st art s wit h a m odule- level declaration of t he cnn1 obj ect reference as a SqlConnect ion obj ect . A m odule- level declarat ion isn’t st rict ly necessary in the Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. cont ext of this sam ple, but t his type of declarat ion m akes t he SqlConnect ion obj ect available t o ot her procedures t hat could use it . I n any event , not ice t hat the declarat ion specifies t he full nam e for t he nam espace cont aining the SqlConnect ion obj ect reference. This is because the m odule doesn’t include an I m ports st at em ent for t he Syst em .Data.SqlClient nam espace. By not using t he I m ports st at em ent at t he top of t he For m 3 module, the Catch clause in the excerpt m ust reference a Syst em except ion instead of the m ore specific SqlClient except ion. I n spit e of this deviat ion from the sam ple in t he “Cat ching SqlConnect ion Except ions” sect ion, SqlClient ex cept ions st ill percolat e up through the m ore general Sy st em except ion specificat ion. Aside from the declarat ion issues for cnn1, the balance of t he code excerpt is a st raightforward m ixt ure of t he code sam ples developed previously in this chapter. Based on whet her RadioButton1 is checked, t he But t on1_Click event procedure com poses a connection string for eit her a Windows or a SQL Server login. Then the procedure inst ant iates a connect ion based on t he connect ion st ring. Wit hin a Try…Catch…Finally st at em ent , t he procedure at t em pts t o open t he connect ion. I f the attem pt succeeds, t he procedur e displays a m essage confirm ing t he at t em pt was successful and nam ing the database. Ot her wise, cont rol flows t o t he Cat ch clause, and t he procedure displays t he error m essage associat ed wit h t he except ion. Because SqlClient except ions percolate up through t he Syst em except ion, t he m essage is likely t o be specific and helpful for diagnosing any problem s. ‘Using the full namespace name removes the need to ‘start module with Imports System.Data.SqlClient. Dim cnn1 As System.Data.SqlClient.SqlConnection Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ’Make local variable declarations. Dim strDBName As String = TextBox1.Text Dim strConnect As String ’Compose a connection string for either a Windows ’or a SQL Server login. If RadioButton1.Checked = True Then strConnect = “Data Source=(local);” & _ “Initial Catalog=“ & strDBName & _ “;Integrated Security=SSPI" Else Dim strLogin As String = TextBox2.Text Dim strPassword As String = TextBox3.Text strConnect = “Data Source=(local);” & _ “Initial Catalog=“ & strDBName & “;” & _ “user id=“ & strLogin & _ “; password=“ & strPassword End If ’Instantiate a SqlConnection object based on the ’connection string. cnn1 = _ New System.Data.SqlClient.SqlConnection(strConnect) ’Embed the attempt to open the cnn1 object inside a ’Try .Catch .Finally statement, and display a ’message for the exception if there is one. Try cnn1.Open() MsgBox(“Successfully connected to “ & cnn1.Database & _ “ database on local server.”) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Catch er As System.Exception MsgBox(er.Message) End Try End Sub W or kin g w ith Com m a nd and Da taRea der Obj ect s One of the m ost com m on uses for Com m and obj ect s is to contain t he SQL st ring that defines t he values cont ained in a Dat aReader object . Therefore, this sect ion drills down on t hat use for Com m and obj ect s. I n this sect ion, you learn how to form at the display of values in a DataReader obj ect as well as how t o populat e a Dat aReader wit h either a SQL st ring or a stored procedure. Beyond t hese typical applicat ions for Com m and obj ect s with Dat aReader obj ect s, the sect ion also includes a sam ple t hat dem onst rat es how to use t he Com m and obj ect for dat a definit ion task s, such as creating a user- defined funct ion. Th e present ation of t he topic covers a special m et hod for Com m and obj ect s t hat is appropriat e when t he Com m andText propert y for a Com m and obj ect doesn ’t ret urn any values. Displaying Result s in a M essage Box or t he Ou tput W indow I t ’s easy t o put SqlCom m and and SqlDataReader obj ect s t o use for report ing results from a SQL Ser ver database. St art by connect ing to t he rem ot e dat a source from which you want t o display result s. Next declare a Com m and obj ect as a SqlCom m and type. The Com m and obj ect requires two input s: a dat abase connect ion and a source of SQL st atem ents t o ex ecut e. You can link a Com m and obj ect t o a Connect ion obj ect when you instant iate t he Com m and object . Specify a data source for t he Comm and obj ect to return wit h either a SQL st ring or a st ored procedure. This capabilit y of com m ands t o take SQL st at em ent s and st ored procedures allows you to draw on all dat a access t opics covered in Chapters 3 t hrough 5. Dat aReader object s read t he result set returned by Com m and obj ect s. Use the ExecuteReader m et hod on a Com m and obj ect t o convey it s r esult set to a Dat aReader object . After the invocat ion of the Execut eReader m et hod, you can ext ract sequent ial rows from a result set wit h the Read m et hod for the Dat a- Reader obj ect. Use one of t he Dat aReader Get m ethods t o ext ract the value for a specific colum n int o a data t ype designated by t he Get m et hod. Colum ns are designated wit h index num bers of 0 t hrough 1 less t han t he number of colum ns in a result set. The Enum erat eCategories procedure, w hich appears next, dem onst rat es t he applicat ion of t hese guidelines for using Com m and and DataReader object s. You can inv ok e this pr ocedure fr om Module1 in t he My ADODOTNETSam ples solut ion by adapting t he inst ruct ions for running ot her procedur es from Module1. The procedure enum erat es Cat egoryI D and CategoryNam e values from t he Cat egories table in t he Nort hw ind dat abase. A com piler const ant , bolOut putWindow , perm its you t o direct the content s of a Dat aReader obj ect to eit her a m essage box or the Output window in the Visual St udio .NET design environm ent. The default value for bolOut put Window direct s the DataReader contents t o a message box. After assigning a v alue t o the com piler const ant, the Enum erat eCategories list ing begins by declaring and inst ant iat ing cnn1 as a Connect ion obj ect befor e invoking the object ’s Open m ethod. Next t he procedur e declares cm d1 as a Com m and obj ect and specifies cnn1 as its Connect ion propert y wit h t he Creat eCom m and m et hod for cn n1. The list ing proceeds t o assign a SQL st ring to t he Com m andText propert y for cm d1. Wit h an ExecuteReader m et hod in a declarat ion for t he drd1 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Dat aReader, the procedure generat es a r esult set for drd1 based on t he SQL st ring used to define cm d1. N ote Throughout this chapter , and elsewhere in t he book, I use generic t erm s interchangeably when referencing specific classes in t he Syst em .Data.SqlClient nam espace. For example, I use the term DataReader to reference t he m ore specific class nam e SqlDat aReader. Using the generic term rem inds y ou t hat SqlClient classes hav e parallel classes in ot her .NET data providers, nam ely t he OLE DB .NET data provider and the ODBC .NET dat a provider. After t he conclusion of t he ExecuteReader m et hod, t he Dat aReader obj ect is ready t o expose it s contents t o a Visual Basic .NET applicat ion. The balance of t he procedure int roduces you t o t wo different st rat egies for achiev ing this. A com piler I f…Then…Else st atem ent based on a com piler const ant adds one of t wo st atem ents t o t he com piled version of t he procedure. Either st at em ent ret urns a row from t he DataReader obj ect , but t hey display the row in different ways. Alt hough t he list ing sh ows bot h the Then and Else clauses, t he com piled procedure contains only one or t he other clause based on the com piler const ant value for bolOut putWindow. Before encountering t he com piler I f…Then…Else st atem ent, the procedure declares a str ing constant that can serve as a t it le for the enum erat ed values in a m essage box. The constant ends wit h a St r Dup funct ion that can duplicate a st ring const ant any num ber of tim es. I n this case, the funct ion appends t w o carriage ret urns t o t he end of the text for t he t it le. Th e int rinsic constant , vbCr, denot es the st ring equivalent of a carr iage return. Next t he procedure starts a Do…While st atem ent wit h the condit ion drd1.Read() . This condit ion will ret urn t he value True as long as t here are rem aining rows in the Dat aReader. After the Read m et hod passes t hrough all the rows from t he drd1 obj ect, the condit ion returns the value False, which causes cont rol t o pass to the first st at em ent aft er the Loop st at em ent for t he Do…While st at em ent . The com piler I f…Th en…Else st atem ent com piles one of t w o possible st atem ents depending on t he value of bolOut putWindow. When bolOut put Window equals its default value ( False), the st at em ent appends Cat egoryI D and Cat egoryNam e values for t he current row to a st ring value. The values for each row end wit h a carriage return (vbCr) . I f bolOutput Window equals True, Visual Basic .NET com piles a different st at em ent that sim ply echoes t he row values t o t he Out put window w it h t he Wr it eLine m et hod for a Console obj ect . Notice t hat t he t wo com piled st at em ents use slightly different techniques for capt uring t he first colum n value for CategoryI D. Both stat em ents use a GetI nt32 m et hod because the SQL Server dat a t ype of int for Cat egoryI D is consistent wit h t he .NET value type of I nt32, a 32- bit signed int eger. However, the pat h for adding the values t o a st ring for display in a m essage box invok es the ToSt ring m et hod to conv ert explicit ly t he I nt 32 num ber t o a st ring. This kind of conversion is preferred because it saves t he t im e for a run-t im e det erm inat ion of how to finally represent a ret urned value. Sub EnumerateCategories() ’Compiler constant directing output to Output window ’or a message box. Default value is False. #Const bolOutputWindow = False ’Declare and open connection to Northwind. Dim cnn1 As SqlConnection = New _ SqlConnection(“Data Source=(local);” & _ “Integrated Security=SSPI;Initial Catalog=northwind”) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. cnn1.Open() ’Declare a command and assign a SQL string to it. Dim cmd1 As SqlCommand = cnn1.CreateCommand() cmd1.CommandText = _ “SELECT CategoryID, CategoryName FROM Categories" ’Declare a data reader and copy result set from SQL string ’for cmd1 to drd1. Dim drd1 As SqlDataReader = cmd1.ExecuteReader() ’Loop through data reader and display in Output ’window or message box. Dim str1 As String = _ “Summary of CategoryID and Category Names” _ & StrDup(2, vbCr) Do While drd1.Read() #If bolOutputWindow = True Then Console.WriteLine(“Category “ & drd1.GetInt32(0) & _ “ is “ & drd1.GetString(1)) #Else str1 = str1 & “Category “ & _ drd1.GetInt32(0).ToString & _ “ is “ & drd1.GetString(1) & vbCr #End If Loop ’Conditionally display results in a message box. #If bolOutputWindow = False Then MsgBox(str1) #End If ’Close data reader and connection object references. drd1.Close() cnn1.Close() End Sub After control passes from the Do…While st atem ent , cont rol can flow opt ionally to a MsgBox funct ion st atem ent for displaying t he st ring com put ed in t he loop. A com piler I f…Th en stat em ent inserts t he MsgBox funct ion into t he com piled procedure if bolOut put Window equals False. Figure 10- 5 shows t he outcom e from the procedure when t he value of bolOutputWindow is False, and Figure 10-6 is an excerpt from t he Output window generated when bolOutput Window is Tr ue. No m att er w hich path t he procedure takes t o generat e resu lt s, it ends by closing the drd1 and cnn1 obj ect references. You should always per form these t ask s when you no longer need a Dat aReader obj ect so that SQL Server can m ake t he connect ion available for ot her requirem ents. Figur e 1 0 - 5 . Ret u rn for t h e Enu m e rat eCat e gories pr ocedu re w he n bolOu t put W indow equ als Fa lse . Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figur e 1 0 - 6 . An ex cerp t from th e ret urn for th e Enum era t e Cat e gories pr ocedur e w h en bolOu t pu t W indow equ als Tru e . Displaying Row s in Blocks fr om a Dat aRea der The preceding sam ple dem onst rat es how conv enient a m essage box can be for display ing t he cont ents of a Dat aReader obj ect . However, a single m essage box can be filled t o its charact er lim it before it com plet es displaying results from a Dat aReader object . A workar ound t o t his situat ion is t o display your result s fr om the Dat aReader obj ect s in blocks of x row s at a tim e. When your application displays rows in blocks, users can sequentially page t hrough a resu lt set to find an item , or it em s, of interest. Because the Dat aReader provides forw ard- only data access, you cannot page back, but you can provide your users a forward- only look at som e data. The Enum erat eCust om erI DNam es procedure allows a user to sp ecify t he num ber of row s t o sh ow in a m essage box. The procedure ret urns the Cust om erI D and Com panyNam e colum n values from the Cust om ers t able in t he Nort hw ind database. You can invoke t he Enum erat eCustom erI DNam es procedure fr om the m ain procedure in Module1. Launching this procedure is slight ly differ ent t han wit h preceding sam ples from Module1. I n t his case, you m ust pass along an argum ent value as you invoke t he procedure. The argum ent is for t he m axim um num ber of rows t o show in a t ext box. The result set fr om t he Com m and obj ect for a Dat aReader object m ay ext end over sever al blocks and require m ultiple m essage box es. Each m essage box , except the final one, m ust hold t he m axim um num ber of rows per block passed as an argum ent t o the Enum erateCust om erI DNam es procedur e. The final m essage box will display from one row up t o t he m axim um num ber of rows. The Enum erat eCust om erI DNam es procedure st arts in t he sam e general fashion as t he preceding one in t hat it m akes a connect ion t o t he Northw ind dat abase and then populates a DataReader, drd1, w ith the result s of a Com m and object, cm d1. The sole dist inct ion in how t he tw o procedures st art is t hat t his one has a different SQL st ring for the Com m and obj ect that ret urns m ore rows t han t he one in the earlier sam ple. This larger num ber of r ows in t he Dat aReader for this sam ple calls for special t reat m ent because a single m essage box cannot display all its rows. The balance of the procedure dem onst rat es one solut ion for the problem of too m any rows t o display in a m essage box. Two code blocks facilitate t he solution. The first block it erat es t hr ough the rows in drd1 in blocks of int Size. The procedure obt ains a value for int Size as a passed argum ent from t he procedur e Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. that calls t he Enum erat eCust om erI DNam es pr ocedure. A user can specify a block size t hat does fit within a single m essage box no m at t er how m any rows are in the Dat aReader. By clicking OK on each m essage box, the user can view successive blocks of rows from t he Dat aReader. The second code block captures any rem aining rows at the end of a Dat aReader obj ect t hat don’t fill a com plet e block . The first code block uses int 1 as a variable t o count t he cum ulat ive num ber of rows read from t he drd1 DataReader. A st ring variable, st r1, accum ulates rows in successive blocks of size int Size. The first code block uses a Do…While st atem ent wit h a condit ion of drd1.Read() t o pass successively t hrough all the rows in the drd1 DataReader . As the code block reads each new row, it recom put es st r1 so that t he new row appears at the bot t om of t he st ring variable. When t he rem ainder of int 1 divided by int Size equals 0, the procedur e accum ulat es a new block of rows ( of size int Size) t o display in a m essage box. The expression int1 mod intSize ret urns t he rem ainder of int1 divided by int Size. When the first code block detect s t he end of a block of rows, t he st ring variable st oring row values is passed to a MsgBox funct ion as t he m essage argum ent . Aft er printing the m essage, t he procedure resets t he st ring variable st r1 t o st art a new block of rows. Then t he whole process st arts over again. When no m ore rows rem ain in the DataReader, the procedure passes cont r ol to the second code block. This second block starts by test ing t o see whet her any rows rem ain t hat didn’t appear since t he display of t he last m essage box. Any rem ainder of int 1 divided by int Size signals undisplayed rows. I f there are any of t hese r ow s, t he second code block passes t he value of st r1 to a MsgBox funct ion as t he m essage argum ent t o show them . The pr ocedure concludes in t he st andard way by closing t he Dat aReader object and its Connect ion obj ect . Sub EnumerateCustomerIDNames(ByVal intSize As Integer) ’Declare and open connection to Northwind. Dim cnn1 As SqlConnection = _ New SqlConnection(“Data Source=(local);” & _ “Integrated Security=SSPI;Initial Catalog=northwind”) cnn1.Open() ’Declare command and assign a SQL string to it, and then ’declare a data reader and copy result set from cmd1 to drd1. Dim cmd1 As SqlCommand = cnn1.CreateCommand() cmd1.CommandText = _ “SELECT CustomerID, CompanyName FROM Customers" Dim drd1 As SqlDataReader = cmd1.ExecuteReader() ’Loop through data reader in blocks of intSize and sequentially ’display the contents of successive blocks. Dim int1 As New Integer() Dim str1 As String = _ “CustomerID and matching CompanyName column values” _ & StrDup(2, vbCr) Do While drd1.Read() str1 = str1 & drd1.GetString(0) & vbTab & _ drd1.GetString(1) & vbCrLf int1 += 1 If (int1 Mod intSize) = 0 Then str1 = str1 & StrDup(2, vbCr) & _ “Click OK for next “ & _ intSize.ToString & “ customers." MsgBox(str1, , “CustomerID and Customer Name”) str1 = _ “CustomerID and matching CompanyName “ & _ “column values” & StrDup(2, vbCr) End If Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Loop ’If a partial block remains at end of data reader contents, ’display partial block. If (int1 Mod intSize) > 0 Then str1 = str1 & StrDup(2, vbCr) _ & “Click OK to close message box." MsgBox(str1, , “CustomerID and Customer Name”) End If ’Close data reader and connection object references. drd1.Close() cnn1.Close() End Sub Figure 10- 7 show s t he first and last m essage boxes that resu lt from running the Enum erateCust om erI DNam es procedur e with an int Size argum ent value of 25. The first m essage box cont ains 25 row s, as do all t he intervening m essage boxes up until t he last one. Th e last m essage box shows t he rows rem aining at t he end that don’t fill an ent ire block of 25 rows. Figur e 1 0 - 7 . The first an d last m essage boxes displayed by th e En u m er a t e Cu st om erI D N a m e s proce du r e. I n vok ing a St or ed Procedur e w it h a Par am et er by a SQL St ring I n addit ion t o using SQL st rings t o designat e t he data for the Com m and obj ect s that populate DataReader object s, you can also specify a st ored procedure as t he source for a Com m and obj ect . There are t wo m ain advantages to using st ored procedures. First , st ored procedures are com piled. This saves t he server the t im e Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. of com piling a SQL st ring before it can st art t o return dat a for your Dat aReader obj ect . Second, st ored procedures accept param et ers. This allows the users of your applicat ions to change t he result set ret urned at run t im e. There ar e two approaches t o set t ing param eter values for st ored procedures. Many developers prefer t o specify a SQL st ring t hat invokes t he stored procedure and passes t he value. Chapt er 4 illust rat es the synt ax for accom plishing this, and we dem onst rate t he use of t he t echnique in a .NET Fram ework applicat ion wit h the sam ple for t his sect ion. A second approach is to add param eters wit h the .NET Fram ew ork syntax. This approach allows you t o explicit ly specify t he data type as you pass a param et er. I will dem onst rat e t his second approach in t he next sect ion. The sam ple for t his sect ion and the next one depends on the Cust OrderHist st ored procedure in t he Nort hw ind database. This procedure ret urns the quantit y of each product ordered by a cust om er. The procedure takes a five- charact er st ring param et er to designate t he Cust om erI D value. The result set cont ains a single r ow for each product ever ordered by a cust om er. Each row cont ains the product nam e and quant ity ordered by t he cust om er specified in t he param et er when you invoke the st ored procedure. For y our convenience in understanding the logic of t he CustOrderHist st ored pr ocedure, here’s t he T- SQL code for the st ored procedure: CREATE PROCEDURE CustOrderHist @CustomerID nchar(5) AS SELECT ProductName, Total=SUM(Quantity) FROM Products P, [Order Details] OD, Orders O, Customers C WHERE C.CustomerID = @CustomerID AND C.CustomerID = O.CustomerID AND O.OrderID = OD.OrderID AND OD.ProductID = P.ProductID GROUP BY ProductName Two sub procedur es m ake up t he solut ion for displaying the results from running the Cust OrderHist st ored procedure w it h a SQL st ring. Th e first sub pr ocedure, RunCustOrderHist Wit hSt ring, invok es t he SQL string for t he st ored pr ocedure and creat es a Dat aReader obj ect based on its result set . RunCust OrderHist WithString takes two argum ents— one for t he Custom erI D value and a second for specifying the m ax im um num ber of r ows t o display as a block in a m essage box. This init ial Visu al Basic .NET procedure: • Creat es a Connect ion obj ect . • I nst ant iates a Com m and obj ect that execut es t he Cust OrderHist st ored procedure while passing a Cust om erI D value as a param eter. • Populat es a DataReader based on t he result set fr om Cust OrderHist . Because t he sam ple uses a SQL st r ing to invoke t he st ored procedure and pass a param eter, t he pr ocess of running a st ored procedure wit h a param et er is sim ilar to j ust specifying a SQL st ring as t he source for t he Com m and obj ect . This sim ilarity is the chief advantage of using t he SQL st ring to inv oke the st ored procedure. One disadvant age of t he approach is t hat t he server has t o com pile the T-SQL st atem ent in t he st ring t o invoke the st ored procedure. Anot her disadvant age is t hat you don’t get the benefit of explicit dat a t yping for t he param eter value at t he client end of t he solut ion. This explicit typing can allow you t o catch inappropriate param et er values earlier in t he solut ion and save server t im e devoted to detecting er roneous param eter values as well as passing back feedback on t he error t o the client. The solution’s second sub procedure, drdToMessageBox, displays the rows in the Dat aReader creat ed by RunCust OrderHist WithSt ring. The drdToMessageBox procedure requires four argum ent s. The first t w o ar e passed by reference inst ead of in t he norm al Visual Basic .NET way of by value. Th ese argum ent s are for t he Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Dat aReader obj ect and its associated Connect ion obj ect . The second tw o argum ent s ar e passed by value. These are the Cust om erI D param et er value and the value for t he m axim um num ber of rows t o display in a m essage box. The design of t his second sub procedure is a direct extension of pr ior sam ples wit h specific adj ust m ents, such as for t he title wit hin a m essage box. A specific benefit of dividing the solut ion across t wo sub procedures is t hat we w ill be able t o reuse this second sub pr ocedure in the next sect ion’s sam ple. Sub RunCustOrderHistWithString(ByVal CustomerID As String, _ ByVal intSize As Integer) ’Declare and open connection to Northwind. Dim cnn1 As SqlConnection = _ New SqlConnection(“Data Source=(local);” & _ “Integrated Security=SSPI;Initial Catalog=northwind”) cnn1.Open() ’Declare command with T-SQL for a stored proc with a parameter. Dim cmd1 As SqlCommand = _ New SqlCommand(“EXEC CustOrderHist “ & CustomerID, cnn1) ’Declare data reader and populate with result set ’from stored procedure. Dim drd1 As SqlDataReader = cmd1.ExecuteReader() ’Display result set. drdToMessageBox(drd1, cnn1, CustomerID, intSize) End Sub Sub drdToMessageBox(ByRef drd1 As SqlClient.SqlDataReader, _ ByRef cnn1 As SqlClient.SqlConnection, _ ByVal CustomerID As String, _ ByVal intSize As Integer) ’Declare header for report in message box and counter for rows ’showing within a message box. Dim str1 As String = _ “Quantities for Products Ordered by “ & _ CustomerID & StrDup(2, vbCr) Dim int1 As Integer ’Loop through data reader in blocks of intSize and ’sequentially display the contents of successive blocks. Do While drd1.Read() str1 = str1 & drd1.GetInt32(1) & vbTab _ & drd1.GetString(0).ToString & vbCrLf int1 += 1 If (int1 Mod intSize) = 0 Then str1 = str1 & StrDup(2, vbCr) _ & “Click OK for next “ & _ intSize.ToString & “ customers." MsgBox(str1, , “From CustOrderHist Stored Proc”) str1 = _ “Quantities for Products Ordered by “ & _ CustomerID & StrDup(2, vbCr) End If Loop ’If a partial block remains at end of data reader contents, ’display partial block. If (int1 Mod intSize) <> 0 Then Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... Dim cmd1 As SqlCommand = New SqlCommand(str1, cnn1) cmd1.ExecuteNonQuery() ’Define SQL string to create a new user-defined function, ’then run the T -SQL batch with ExecuteNonQuery method ’for a command str1 = “CREATE FUNCTION udfDaysDiffLessx” & _ “(@date1 as datetime, @date2 as datetime, “ & _ “@x as Integer) “ & _ “RETURNS int “ & _ “AS “ & _ “BEGIN “ & _ “Return(DATEDIFF(day,@date1,@date2 )-@ x) “ &... Optional ByVal strx As String = “1”) ’Declare and open connection to Northwind Dim cnn1 As SqlConnection = _ New SqlConnection(“Data Source=(local);” & _ “Integrated Security=SSPI;Initial Catalog=northwind”) cnn1.Open() ’Define SQL string to drop prior version of user-defined ’function, then run the T -SQL batch with ExecuteNonQuery ’method for a command Dim str1 As String = _ “IF EXISTS “ & _ “(SELECT... stored proc Dim cmd1 As SqlCommand = _ New SqlCommand(“CustOrderHist", cnn1) cmd1.CommandType = CommandType.StoredProcedure ’Declare the parameter with a SqlDbType to eliminate ’the need for conversion, then assign the parameter a value Dim prm1 As SqlParameter = _ cmd1.Parameters.Add(“@CustomerID", SqlDbType.NChar, 5) prm1.Value = CustomerID ’Declare data reader and populate with its result ’set from... “Return(DATEDIFF(day,@date1,@date2 )-@ x) “ & _ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark “END" cmd1.CommandText = str1 cmd1.ExecuteNonQuery() ’Define a SQL string to use the preceding user-defined ’function and accept variables for SQL string ’(strx and intOrderNo), then assign SQL string to ’CommandText property of command(cmd1) Dim strSQL As String strSQL = “SELECT LEFT(OrderDate,11) AS ’Order... form Dim cmd1 As SqlCommand = _ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark New SqlCommand _ (“SELECT CategoryID, CategoryName, Description “ & _ “FROM Categories", _ cnn1) Dim dap1 As SqlDataAdapter = New SqlDataAdapter() dap1.SelectCommand = cmd1 cnn1.Open() ’Fill the data set (das1) with the data adapter dap1; ’the Fill method populates the data set with a table ’named... Shipper st ored procedure on your local SQL Serv er inst ance By inv ok ing t he following T- SQL script in Query Analyzer , y ou can cr eat e udpI nsert ANew Shipper on t he SQL Serv er inst ance t o which you connect The first t wo TSQL bat ches connect t o t he Nort hwind dat abase and elim inat e any prior version of t he st ored pr ocedur e The last T- SQL bat ch in t he script is a CREATE PROCEDURE... o creat e or drop See Chapt er 5 for t he T- SQL synt ax on adding and rem ov ing user - defined funct ions and Chapt er 7 for a discussion of t he secur it y associat ed wit h logins t o a SQL Serv er inst ance I f your login is t he adm inist rat or for y our local inst ance of SQL Serv er, you hav e appropriat e perm ission t o r un t he sam ple The user - defined funct ion udfDaysDiffLessx in t... Dim dap1 As SqlDataAdapter = New SqlDataAdapter() dap1.SelectCommand = cmd1 cnn1.Open() ’Fill the data set (das1) with the data adapter dap1; ’the Fill method populates the data set with a datatable ’named Categories notice that the datatable Categories ’isn’t the same as the Categories table in the ’Northwind database das1 = New DataSet() dap1.Fill(das1, “Categories”) ’Re-specify the SQL string for... parameter with a SqlDbType, then assign ’the parameter a value based on a public variable ’whose value is passed from another form Dim prm1 As SqlParameter = _ cmd1.Parameters.Add(“@country", SqlDbType.NVarChar, 15) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark prm1.Value() = Country ’Assign cmd1 to the SelectCommand property of dap1, then ’open dap1 Dim dap1 As SqlDataAdapter... abilit y t o oper at e w hile disconnect ed adds t o t he scalabilit y of Visual Basic NET applicat ions for SQL Ser ver ’Module-level declaration of data set object Dim das1 As DataSet = New DataSet() Sub Populate() ’Specify a connection for a data adapter that ’fills the data set used on the form Dim cnn1 As SqlConnection = _ New SqlConnection _ (“Data Source=(local);” & _ “Integrated Security=SSPI;” . As SqlCommand = New SqlCommand(str1, cnn1) cmd1.ExecuteNonQuery() ’Define SQL string to create a new user-defined function, ’then run the T -SQL batch with. Catalog=northwind”) cnn1.Open() ’Declare command with T -SQL for a stored proc with a parameter. Dim cmd1 As SqlCommand = _ New SqlCommand(“EXEC CustOrderHist “ &

Ngày đăng: 24/12/2013, 02:18

Từ khóa liên quan

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

Tài liệu liên quan