Logo of VovisoftMastering Visual Basic 6

Chương 6 _Phần 4 : Executing statement on a database

    SQL Server và Visual Basic có quan hệ với nhau trong gịng họ Microsoft.  Do quan hệ này mà các bạn có thể tiến hành SQL statements một cách trực tiếp.  Với Execute method, các bạn có thể xử dụng SQL statement trong Connection object hay Command object dể dàng. SQL statments là ǵ ? Ở đây chúng ta hiểu là mệnh lệnh viết trong ứng dụng của Visual Basic và mệnh lệnh này SQL Server nghe theo.  Mời các bạn theo dỏi chúng tôi tŕnh bày sự quan hệ này.

    Chúng ta có một ứng dụng như sau : có connection giửa Client và Server.  User Interface của ứng dụng như thế này

    Trong Form load, chúng ta cho tiến hành Connection và Database được thông thương giửa kho nhu liệu và người xử dụng.  Code được viết như thế này.

    Ứng dụng này c̣n có mệnh lệnh Insert, nghỉa là thêm vào chi tiết trong bản tài liệu.  Code được viết như thế này

    Mệnh lệnh được truyền từ Visual Basic application tới Database trong SQL Server.  Code được viết như thế này.

    Và với cách t́m kiếm tài liệu này, ứng dụng của các bạn sẽ làm việc rất có hiệu quả, v́ mệnh lệnh được chỉ thị một cách trực tiếp.  Từ chuyên nghiệp gọi là executing statement directly.

Chương 6 _Phần 4 _Đoạn 1 : Executing Directly Using the Connection Object

    Nếu SQL command chỉ cần tiến hành một lần thôi trong ứng dụng của các bạn, th́ hăy nên xử dụng Execute method cho active connection.  Phương pháp này làm việc rất có hiệu quả, nếu mệnh lệnh chỉ truyền đi chỉ một lần thôi.  Đây là thí dụ làm sao để cài đặt SQL command vào trong ứng dụng.

Sub cmdUpdateRecords_Click()

 

         Dim cnStateUBookstore As Connection

         Dim sSQL As String

 

         Set cnStateUBookstore = New Connection

 

         With cnStateUBookstore

                  .Provider = "SQLOLEDB"

                  .ConnectionString = "User ID=sa;" & _

                                      "Data Source=MSERIES1;" & _

                                      "Initial Catalog=StateUBookstore"

                  .Open

         End With

 

         sSQL = "INSERT INTO Authors(First_Name, Last_Name) " & _

                  "VALUES ('Suanne', 'Nagata')"

 

         cnStateUBookstore.Execute sSQL

 

End Sub

    Executing Directly Using the Command Object : Nếu SQL command mà được xài đến nhiều hơn 1 lần trong cùng một ứng dụng th́ phương pháp tốt nhất là xử dụng Command Object.  Để làm việc này, các bạn sẽ phải set Prepared property thành True.  Kỷ thuật này giúp cho việc tiến hành mệnh lệnh có nhiều hiệu quả.  Bất lợi của nó là nó sẽ tiến hành công việc lâu hơn nếu so với việc các bạn xử dụng connection object.  Nhưng nếu SQL command phải gọi tới nhiều lần th́ tốt hơn hết các bạn nên xử dụng Command object.  Mời các bạn theo dỏi sau đây là click event dẩn giải làm sao để cài đặt SQL command vào trong Command Object.

Sub cmdUpdateRecords_Click()

         Dim cnStateUBookstore As Connection

         Dim comBooks As Command

         Set cnStateUBookstore = New Connection

         With cnStateUBookstore

                  .Provider = "SQLOLEDB"

                  .ConnectionString = "User ID=sa;" & _

                                      "Data Source=MSERIES1;" & _

                                      "Initial Catalog=StateUBookstore"

                  .Open

         End With

 

         Set comBooks = New Command

         With comBooks

                  .Prepared = True

                  .ActiveConnection = cnStateUBookstore

                  .CommandType = adCmdText

                  .CommandText = "UPDATE Books SET Price = Price * 1.1"

         End With

 

         comBooks.Execute

End Sub

Chương 6 _Phần 4 _Đoạn 2 : Overview of Stored Procedure

    Stored Procedures là ǵ ? Là những kế hoạch hành động  được cất giử ở phía Server và sẽ được tiến hành khi ứng dụng ở phía Client gọi đến.  Stored procedures are routines that are stored on the server and can be executed from a single call from a client.  Những stored procedures phức tạp được viết dưới dạng scripting language mà từ chuyên nghiệp gọi là Transact SQL.  Transact SQL được hoán chuyển và cất ở SQL Server Database

    Stored procedure rất là hữu ích cho việc viết ứng dụng, nếu ứng dụng của bạn có liên quan đến việc thông thương với SQL Server Database.  Ngoài việc thay đổi (modify), thêm (insert), bớt (delete), stored procedure c̣n có thể bảo đảm việc trao đổi data một cách hoàn chỉnh nếu có sự thay đổi về business rules.  Có nghĩa là hành động được cất ở Server, nhưng sẽ không xử dụng đến nếu phía client không gọi đến v́ không có sự thay đổi về business rules.  Nhưng nếu có sự thay đổi về business rules th́ lập tức stored procedure sẽ tiến hành.

    Thí dụ như bạn có ứng dụng về đổi tiền, từ tiền nước này sang nước khác.  Thông thường th́ bạn phải trả commission, theo luật lệ.  Nhưng để khuyến khích việc du khách vào nước, luật lệ có thể thay đổi là không cần phải trả commission.  Th́ procedure đă giử sẳn ở Server sẽ tiến hành khi phía client cho hay là có thay đổi và gọi stored procedure đó.

Advantages of Stored Procedures :

® Accept parameters.  Có thể cung ứng Data, mặc dù Data được cất giử qua nhiều tầng lớp dưới dạng parameters

® Return values of parameters to a calling procedure or client.  Cung ứng Data cho procedure và cả client

® Return a status value that indicates success or failure, as well as the reason for the failure. Báo cáo t́nh trạng của Data trong mọi t́nh huống nào.

® Call other stored procedures.  Có thể gọi những stored procedure khác.

® Encapsulate business functionality so that all applications can use and perform the procedures consistently. Thâu gồm luôn cả chuyện thay đổi dự luật, giúp các bạn có thể xử dụng object này cho nhiều ứng dụng.

® Make execution faster and more efficient. Once they are compiled no syntax checking is required when they are executed.  Chương tŕnh tiến hành sẽ nhanh chóng hơn và hiệu quả hơn.  Một khi stored procedure đă hoán chuyển rồi th́ không cần phải có syntax kiểm tra.

® Store the compiled version on the server and use it for subsequent calls, thus reducing network traffic.  Thành phần đă được hoán chuyển rồi, sẽ giử ở Server và sẳn sàng cho các lần yêu cầu khác, giúp cho việc trao đổi nhanh chóng hơn

® Be called from different client applications.  Có thể phục vụ cho các ứng dụng khác nữa ở phía client.

Chương 6 _Phần 4 _Đoạn 3 : Calling a Stored Procedure

    Các bạn xử dụng ADO Command object để gọi stored procedures.  Theo những bước chính sau đây : 

1.    Create an ADO Command object and set its ActiveConnection property to use a connection to the database containing the stored procedure you want to call.  Tạo thành một ADO Command object và thêm chi tiết vào ActiveConection property là sẽ xữ dụng connection mà chứa đựng stored procedure.

2.    Specify that the command is a stored procedure by setting the CommandType property to adCmdStoredProc.  Xác định CommandType property thành adCmdStoredProc

3.    Specify which stored procedure you want to call by setting the CommandText property to the name of the stored procedure.  Xác định tên của stored procedure vào trong CommandText property

4.    If you need to send data to or receive data from the stored procedure you can use the Parameters collection of the Command object. Nếu trong stored procedure có việc làm là gửi đi hay nhận lấy tài liệu th́ xử dụng Parameters collection của Command object.

           a. Use the Append and CreateParameter methods to create parameters to hold the data.

           b. Use the Direction argument of the CreateParameter method to specify the type of parameter you want to create.

5.       To run the stored procedure, call the Command object's Execute method.  Để stored procedure tiến hành, xử dụng Execute method của Command object

6.       If the stored procedure returns data, you can receive the output either in a recordset or in parameters. More complex stored procedures can return a combination of recordsets and output parameters in a single call.  Nếu stored procedure giao trả Data, các bạn có thể nhận lấy từ recordset hay parameters.  Và những stored procedure phức tạp có thể cung cấp tài liệu tổng hợp từ recordset hay parameters chỉ trong một lần gọi mà thôi.

    Mời các bạn cùng chúng tôi gọi một stored procedure từ trong một command object.  Chúng ta có một ứng dụng là yêu cầu cung cấp cho chúng ta bao nhiêu học sinh ghi danh học môn chánh.

    Thí dụ như môn Lịch sữ.  Người xử dụng sẽ điền vào ô trống con số tượng trưng cho môn học đó và bấm vào nút Ok.  Ứng dụng sẽ cung cấp tài liệu đó cho người xử dụng.

    Sau đây là phần code viết cho mệnh lệnh đó:

Dim rsAuthorInfo As Recordset

Sub cmdGetStudentsByMajor_Click()

 

    Dim cnStateUBookstore As Connection

    Dim comStudentMajor As Command

 

    ' Instantiate the object variables

    Set cnStateUBookstore = New Connection

    Set comStudentMajor = New Command

    Set rsStudentInfo = New Recordset

   

    ' Establish a connection to the database

    With cnStateUBookstore

        .Provider = "SQLOLEDB"

        .ConnectionString = "User ID=sa;" & _

                            "Data Source=MSERIES1;" & _

                            "Initial Catalog=StateUBookstore"

        .Open

    End With

   

    ' Create the Command object

    With comStudentMajor

        .CommandType = adCmdStoredProc

 

        ' set the name of the stored procedure

        .CommandText = "StudentMajor"

 

        ' create and append the input parameter

        .Parameters.Append comStudentMajor.CreateParameter("MajorID", adInteger)

 

        ' set the initial value of the parameter

        .Parameters("MajorID").Value = txtMajorID.Text

 

        ' set the connection

        .ActiveConnection = cnStateUBookstore

    End With

   

    ' call the stored proc and save the results in a recordset

    Set rsStudentInfo = comStudentMajor.Execute

 

End Sub

(...c̣n nữa...mời Quí vị trở lại xem tiếp...)