Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
9,5 Thực hiện phương pháp đó Cập nhật cơ sở dữ liệu Bây giờ bạn có một lớp học mà có thể lấy một hàng cụ thể từ cơ sở dữ liệu, bạn sẽ cần phải thực hiện một phương pháp mà sẽ lưu các thay đổi cơ sở dữ liệu. | 9.5 Implement the Methods That Update the Database Now that you have a class that can retrieve a specific row from the database you will need to implement a method that will save changes to the database. You ll also need a method to insert new rows into-as well as delete existing rows from-the Customers table. Technique In the case of updating and deleting rows in the database you will need to implement the Save and Delete methods that are defined in the ICustomer interface. To insert new rows into the database you ll need to add additional constructors to the class. Having multiple methods with the same name is a new feature in Visual Basic .NET called overloading. In this example you will only overload constructors but you can also overload functions and subs. Steps The first task is to implement the Save and Delete methods that were defined in your interface in section 9.1. You have already set up all the database-access objects you will need so it s just a matter of adding the relevant code. 1. You will need two helper methods for the Save and Delete methods a method whose sole responsibility is to call the update method of the data adapter and a method that clears the properties of the object. Both methods are defined in Listing 9.26. Listing 9.26 frmHowTo9_5.vb The WriteChangesToDB and Clear Methods Private Function WriteChangesToDB ByVal pStateToHandle _ As DataRowState As Boolean Try Create a dataset of only those rows that have been changed specifically those changed in the manner specified by the DataRowState . Dim dsChanges As DataSet mdsCust.GetChanges pStateToHandle Pass this subset of the dataset to the data adapter to write the changes to the database. The data adapter will handle all calls to the Delete Insert and Update commands. odaCustomers.Update dsChanges Catch ex As Exception If the update fails communicate this back to the calling function by returning False. mdsCust.RejectChanges Return False End Try Update the customer s dataset to reflect