Beginning Visual Basic 2005 Databases phần 3 pdf

75 234 0
Beginning Visual Basic 2005 Databases phần 3 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

13. Enter the following query to insert a new group in the Groups table: INSERT INTO Groups (GroupID, GroupName, GroupDescription, LastUpdateDate) VALUES (@GroupID, @GroupName, @GroupDescription, Date()+Time()); 14. Click the Save button on the toolbar or click the File menu and choose Save. In the Save As dialog box, enter a query name of usp_InsertGroup. Once your query has been saved, close the Query Builder window by clicking the X in its upper-right corner. 15. Double-click Create Query in Design View in the Query list to create another query. 16. Close the Show Table dialog box and then click the View button on the toolbar or click the View menu and choose SQL View. 17. Enter the following query to update a group in the Groups table: UPDATE Groups SET GroupName = @GroupName, GroupDescription = @GroupDescription, LastUpdateDate = Date()+Time() WHERE GroupID = @GroupID; 18. Click the Save button on the toolbar or click the File menu and choose Save. In the Save As dialog box, enter a query name of usp_UpdateGroup. Once your query has been saved, close the Query Builder window by clicking the X in its upper-right corner. 19. Double-click Create Query in Design View in the Query list to create another query. 20. Close the Show Table dialog box and click the View button on the toolbar, or click the View menu and choose SQL View. 21. Enter the following query to delete a group in the Groups table: DELETE FROM Groups WHERE GroupID = @GroupID; 22. Click the Save button on the toolbar or click the File menu and choose Save. In the Save As dialog box, enter a query name of usp_DeleteGroup. After your query has been saved, close the Query Builder window by clicking the X in its upper-right corner. 23. Close your Access database. How It Works You’ve already seen how to build queries in Access and you’ve seen how SELECT, INSERT, UPDATE and DELETE queries work, so I’ll just summarize what you do in this section. The first query that you build is the usp_SelectGroups query. This SELECT query does not accept any parameters and selects all rows of data from the Groups table. You specify the columns that you want returned in your results in the select list. SELECT GroupID, GroupName, GroupDescription, LastUpdateDate FROM Groups ORDER BY GroupName; 138 Chapter 7 10_58894x ch07.qxd 10/13/05 5:52 PM Page 138 The next SELECT query that you build is the usp_SelectGroup query. This is a parameter query, meaning that in order to run, it expects a parameter. This query selects a single group from the Groups table based on the GroupID passed as the parameter to this query. SELECT GroupID, GroupName, GroupDescription, LastUpdateDate FROM Groups WHERE GroupID = @GroupID; The INSERT query that you build, usp_InsertGroup, inserts a new row of data into the Groups table. You supply input parameters to this query for the GroupID, GroupName, and GroupDescription columns. The LastUpdateDate column has the current date and time inserted into it using the built-in Access functions Date and Time. INSERT INTO Groups (GroupID, GroupName, GroupDescription, LastUpdateDate) VALUES (@GroupID, @GroupName, @GroupDescription, Date()+Time()); The UPDATE query, usp_UpdateGroup, updates a single group in the Groups table based on the GroupID. Again, you are using the built-in Access functions Date and Time to update the value in the LastUpdateDate column. UPDATE Groups SET GroupName = @GroupName, GroupDescription = @GroupDescription, LastUpdateDate = Date()+Time() WHERE GroupID = @GroupID; The final query that you build is the usp_DeleteGroup query. This query deletes a single row of data from the Groups table, where the value in the GroupID column matches the value passed in the @GroupID parameter. DELETE FROM Groups WHERE GroupID = @GroupID; In this Try It Out, you implement the queries that you just built in your ProjectTimeTracker database in your Time Tracker application. The functionality that you implement in this exercise mirrors the functionality that you implemented for projects in the first exercise in this chapter. You add code to execute your usp_SelectGroups query to populate the Groups list, and the code to execute your usp_SelectGroup query to select and display the details for a single group. You also add the code necessary to insert, update, and delete a group using your usp_InsertGroup, usp_UpdateGroup, and usp_DeleteGroup queries. Try It Out Implementing the Group Queries To implement this functionality: 1. Open the Time Tracker application in Visual Studio 2005 if it is not already open. 2. Switch to the Code Editor for the Admin form and add the following Imports statement: 139 Inserting, Updating, and Deleting Data in Access 10_58894x ch07.qxd 10/13/05 5:52 PM Page 139 Imports System.Data Public Class Admin 3. Now add the following form-level variable declaration: Private objData As WDABase Private objGroupsDS As DataSet 4. Modify the Admin_Load procedure as follows: The IDE displays an error that LoadGroups is not declared, as you’ve not added this procedure yet. Ignore this error for now because you add that procedure in the next step: AddHandler imgUsers.MouseUp, AddressOf NavigationChildControl_MouseUp ‘Display a loading message ToolStripStatus.Text = “Loading ” ‘Set the current date in the date panel in the status bar ToolStripDate.Text = Date.Today ‘Get the application title strAppTitle = My.Application.Info.Title ‘Show the form and refresh it Me.Show() Me.Refresh() ‘Load the Projects LoadProjects() ‘Load the Groups LoadGroups() ‘Display a ready message ToolStripStatus.Text = “Ready” End Sub 5. The LoadGroups procedure executes your usp_SelectGroups query to select all groups in the Groups table. Create the LoadGroups procedure and add the following code to it: Private Sub LoadGroups() ‘Declare variables Dim objListViewItem As ListViewItem ‘Initialize a new instance of the data access base class Using objData As New WDABase Try ‘Clear previous data bindings cboGroups.DataSource = Nothing cboGroups.DisplayMember = String.Empty cboGroups.ValueMember = String.Empty ‘Get all Groups in a DataSet object objData.SQL = “usp_SelectGroups” 140 Chapter 7 10_58894x ch07.qxd 10/13/05 5:52 PM Page 140 objGroupsDS = New DataSet objData.FillDataSet(objGroupsDS, “Groups”) ‘Clear previous list lvwGroups.Items.Clear() ‘Process all rows For intIndex = 0 To objGroupsDS.Tables(“Groups”).Rows.Count - 1 ‘Create a new listview item objListViewItem = New ListViewItem ‘Add the data to the listview item objListViewItem.Text = _ objGroupsDS.Tables(“Groups”).Rows(intIndex).Item( _ “GroupName”) objListViewItem.Tag = _ objGroupsDS.Tables(“Groups”).Rows(intIndex).Item( _ “GroupID”) ‘Add the sub items to the listview item objListViewItem.SubItems.Add( _ objGroupsDS.Tables(“Groups”).Rows(intIndex).Item( _ “GroupDescription”)) objListViewItem.SubItems.Add( _ Format(objGroupsDS.Tables(“Groups”).Rows(intIndex).Item( _ “LastUpdateDate”), “g”)) ‘Add the listview item to the listview control lvwGroups.Items.Add(objListViewItem) Next ‘Rebind ComboBox control cboGroups.DataSource = objGroupsDS.Tables(“Groups”) cboGroups.DisplayMember = “GroupName” cboGroups.ValueMember = “GroupID” ‘Reset the selected index cboGroups.SelectedIndex = -1 Catch ExceptionErr As Exception MessageBox.Show(ExceptionErr.Message, strAppTitle) End Try End Using ‘Cleanup objListViewItem = Nothing End Sub 6. The lvwGroups_Click procedure executes your usp_SelectGroup query to select a single group from the Groups table. In the Class Name combo box, select lvwGroups; and in the Method Name combo box, select the Click event to add the lvwGroups_Click procedure to your project. Add the following code to this procedure: 141 Inserting, Updating, and Deleting Data in Access 10_58894x ch07.qxd 10/13/05 5:52 PM Page 141 Private Sub lvwGroups_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles lvwGroups.Click ‘Initialize a new instance of the data access base class Using objData As New WDABase Try ‘Get the specific Group selected in the ListView control objData.SQL = “usp_SelectGroup” objData.InitializeCommand() objData.AddParameter(“@GroupID”, Data.OleDb.OleDbType.Guid, 16, _ lvwGroups.SelectedItems.Item(0).Tag) objData.OpenConnection() objData.DataReader = objData.Command.ExecuteReader ‘See if any data exists before continuing If objData.DataReader.HasRows Then ‘Read the first and only row of data objData.DataReader.Read() ‘Populate the Group Details section txtGroupID.Text = _ objData.DataReader.Item(“GroupID”).ToString.ToUpper txtGroupName.Text = _ objData.DataReader.Item(“GroupName”) txtGroupDescription.Text = _ objData.DataReader.Item(“GroupDescription”) txtGroupUpdateDate.Text = _ Format(objData.DataReader.Item(“LastUpdateDate”), “g”) End If ‘Close the DataReader objData.DataReader.Close() ‘Close the database connection objData.CloseConnection() Catch ExceptionErr As Exception MessageBox.Show(ExceptionErr.Message, strAppTitle) End Try End Using End Sub 7. You want to implement the code to execute your usp_InsertGroup query in the ActionAdd procedure, so modify this procedure as follows: Case “Groups” ‘Set the SQL string objData.SQL = “usp_InsertGroup” ‘Initialize the Command object objData.InitializeCommand() ‘Add the Parameters to the Parameters collection objData.AddParameter(“@GroupID”, _ Data.OleDb.OleDbType.Guid, 16, Guid.NewGuid()) 142 Chapter 7 10_58894x ch07.qxd 10/13/05 5:52 PM Page 142 objData.AddParameter(“@GroupName”, _ Data.OleDb.OleDbType.VarChar, 50, txtGroupName.Text) objData.AddParameter(“@GroupDescription”, _ Data.OleDb.OleDbType.LongVarChar, _ txtGroupDescription.Text.Length, _ txtGroupDescription.Text) ‘Open the database connection objData.OpenConnection() ‘Execute the query intRowsAffected = objData.Command.ExecuteNonQuery() ‘Close the database connection objData.CloseConnection() If intRowsAffected = 0 Then Throw New Exception(“Insert Group Failed”) End If ‘Clear the input fields txtGroupName.Text = String.Empty txtGroupDescription.Text = String.Empty ‘Reload the Groups list LoadGroups() 8. Next, you need to modify the ActionUpdate procedure to execute your usp_UpdateGroup query. Modify this procedure as follows: Case “Groups” ‘Set the SQL string objData.SQL = “usp_UpdateGroup” ‘Initialize the Command object objData.InitializeCommand() ‘Add the Parameters to the Parameters collection objData.AddParameter(“@GroupName”, _ Data.OleDb.OleDbType.VarChar, 50, txtGroupName.Text) objData.AddParameter(“@GroupDescription”, _ Data.OleDb.OleDbType.LongVarChar, _ txtGroupDescription.Text.Length, _ txtGroupDescription.Text) objData.AddParameter(“@GroupID”, _ Data.OleDb.OleDbType.Guid, 16, New Guid( _ txtGroupID.Text)) ‘Open the database connection objData.OpenConnection() ‘Execute the query intRowsAffected = objData.Command.ExecuteNonQuery() ‘Close the database connection objData.CloseConnection() If intRowsAffected = 0 Then Throw New Exception(“Update Group Failed”) End If ‘Clear the input fields txtGroupID.Text = String.Empty txtGroupName.Text = String.Empty txtGroupDescription.Text = String.Empty txtGroupUpdateDate.Text = String.Empty ‘Reload the Groups list LoadGroups() 143 Inserting, Updating, and Deleting Data in Access 10_58894x ch07.qxd 10/13/05 5:52 PM Page 143 9. Modify the ActionDelete procedure to execute the usp_DeleteGroup query. Modify this pro- cedure as follows: Case “Groups” ‘Set the SQL string objData.SQL = “usp_DeleteGroup” ‘Initialize the Command object objData.InitializeCommand() ‘Add the Parameters to the Parameters collection objData.AddParameter(“@GroupID”, _ Data.OleDb.OleDbType.Guid, 16, New Guid( _ txtGroupID.Text)) ‘Open the database connection objData.OpenConnection() ‘Execute the query intRowsAffected = objData.Command.ExecuteNonQuery() ‘Close the database connection objData.CloseConnection() If intRowsAffected = 0 Then Throw New Exception(“Delete Group Failed”) End If ‘Clear the input fields txtGroupID.Text = String.Empty txtGroupName.Text = String.Empty txtGroupDescription.Text = String.Empty txtGroupUpdateDate.Text = String.Empty ‘Reload the Groups list LoadGroups() 10. You are now ready to test the modifications that you have made. Start your project and when the Admin form is displayed, click Groups in the Shortcut navigation pane to display the Groups screen. Of course, no data is displayed, as you have not entered any group data yet. 11. Enter a group name of your choosing in the Name field and a description in the Description field. Click the Add button on the toolbar or click the Action menu and choose Add to have the new group added, as shown in Figure 7-3. 144 Chapter 7 10_58894x ch07.qxd 10/13/05 5:52 PM Page 144 Figure 7-3 Not only will the group be displayed in the Groups list, but it is also added to the ComboBox control on the Group Projects screen. You can click Group Projects in the Shortcuts navigation bar to display the Group Projects screen and then click the Groups ComboBox to see the group listed there. 12. Now you want to test the update functionality by clicking the group you just added in the Groups list and modifying the name and/or description, so navigate back to the Groups screen and click the group to have the group details displayed. Make some modifications to the group name and/or group description. After you have done that, click the Update button on the toolbar or click the Action menu and choose Update. The group is updated and the Groups list is cleared and reloaded with fresh data from the database, displaying your updates to the group. 13. Test the delete functionality, so again click the group in the Groups list to have the group details displayed. Then click the Delete button on the toolbar or click the Action menu and select Delete. 14. When you have finished testing all of the functionality of your application, add three groups of your choosing in preparation for the exercises in the next chapter. When you were testing your code, you tested one query by simply starting your project: the usp_SelectGroups query. This query was executed in the LoadGroups procedure when the form loaded. By adding a new group and having it displayed, as shown in Figure 7-3, you tested two queries in two procedures. The first query that you tested was the usp_InsertGroup query in the ActionAdd procedure. This procedure then called the LoadGroups procedure after the group was inserted into the database, which tested the usp_SelectGroups query. 145 Inserting, Updating, and Deleting Data in Access 10_58894x ch07.qxd 10/13/05 5:52 PM Page 145 The process of updating and deleting a group tested three queries. First you had to click a group in the list to view the details of the group, which tested the usp_SelectGroup query. This query retrieved the group details from the database and displayed them in the Group Details section of your form. Then, when you clicked the Update or Delete icon on the toolbar, the usp_UpdateGroup or usp_DeleteGroup query was executed and a call was made to the LoadGroups procedure. These actions executed the usp_SelectGroups query. Let’s see how this works in detail. How It Works The form level DataSet object that you declare is used to load the group data in. This DataSet is then read and used to load the Groups ListView control. It is also used when it is bound to a ComboBox con- trol containing a list of all the groups in your database. Private objGroupsDS As DataSet When you start loading a lot of data from the database when your application starts, you need to do one of two things to let the user know that your application is busy loading. The first option is to display a splash screen, such as the one displayed when Visual Studio 2005 loads, and the second option is to display your empty form with a message that the application is loading data. The second option is the one you implement here. You implement code in the Admin_Load procedure to set a message in the status bar indicating that the application is loading. Then you display the form by calling the Show method on the form. Notice that you use the Me keyword, which references the current form. Calling the Refresh method on the form after it has been shown forces it to redraw the controls on the form. This ensures that the form controls are properly displayed while the rest of the code in the load procedure executes. ‘Display a loading message ToolStripStatus.Text = “Loading ” ‘Show the form and refresh it Me.Show() Me.Refresh() After you call the LoadProjects procedure, you add code to call the LoadGroups procedure. This procedure loads the Groups list and binds a DataSet to the Groups ComboBox control. After control is returned from the LoadGroups procedure, you display a new message in the status bar to indicate to the user that the application is ready for use. ‘Load the Groups LoadGroups() ‘Display a ready message ToolStripStatus.Text = “Ready” The LoadGroups procedure is added next. The first thing that you do in this procedure is declare an object as a ListViewItem. This enables you to build a ListView item and add it to the ListView control. Next, you initialize a new instance of the WDABase class in your objData object in a Using End Using block. 146 Chapter 7 10_58894x ch07.qxd 10/13/05 5:52 PM Page 146 Private Sub LoadGroups() ‘Declare variables Dim objListViewItem As ListViewItem ‘Initialize a new instance of the data access base class Using objData As New WDABase You implement a Try Catch block to handle any errors that may be encountered while loading the DataSet with data from the database. The first thing that you do inside the Try block is clear the previous bindings of your cboGroups ComboBox control by setting the DataSource property to Nothing. This property is set to the DataSet that contains the data to be bound to the control. The DisplayMember and ValueMember properties are set to an empty string, clearing the String values that get set in these properties. Of course, the first time this procedure is called, the ComboBox control has not yet been bound, but on subsequent executions of this procedure it will have been bound and will need to be cleared. Try ‘Clear previous data bindings cboGroups.DataSource = Nothing cboGroups.DisplayMember = String.Empty cboGroups.ValueMember = String.Empty Next, you set the SQL property of the objData object to the query that will retrieve a list of all groups in the Groups table. Because you will be binding a DataSet to the cboGroups ComboBox control and loading the lvwGroups ListView control with groups, it is more efficient to populate a DataSet with the group data than to use an OleDbDataReader object to load the ListView control and then use a DataSet that will be bound to a ComboBox control. After you set the SQL property, you then initialize a new instance of the DataSet class in your objGroupsDS DataSet object. Then you call the FillDataSet method in your objData object to populate your DataSet object and set the table name in the DataSet to Groups. ‘Get all Groups in a DataSet object objData.SQL = “usp_SelectGroups” objGroupsDS = New DataSet objData.FillDataSet(objGroupsDS, “Groups”) Let’s digress for a moment and take a look at the FillDataSet method in the WDABase class because you haven’t seen this method in detail yet. This procedure accepts the DataSet object that is to be filled with data as the first parameter. The object for this parameter is passed by reference. When you pass an object by reference to a procedure, the procedure that the object is passed to can modify the value of the object in the same manner as the code that called this procedure. What this means is that you can define the object in one class and modify its value there and when you pass this object by reference to a procedure in another class, it behaves as if the object were declared locally within the called procedure. The second parameter to the FillDataSet method is passed by value and is a String value for the table name to be used when the DataSet is populated with data. Passing a parameter by value means that you actually pass the value of the parameter and not a reference to it. 147 Inserting, Updating, and Deleting Data in Access 10_58894x ch07.qxd 10/13/05 5:52 PM Page 147 [...]... the productivity capabilities of Visual Studio 2005 by adding some application configuration settings and a WDABase class to your project just as you’ve used in your Time Tracker application However, you don’t want to have to recode all of that code or have to open the Time Tracker project and copy the code and paste it into this project There’s no need, as Visual Studio 2005 will do this for you automatically... Connections To create this utility: 1 Start Visual Studio 2005 and start a new project by either clicking the Project link on the Recent Projects tab of the Start page or by selecting File ➪ New ➪ Project 2 In the New Project dialog box, select a Windows Application template and enter a project name of DB Migration Utility Click OK to create this project 3 Set the following properties for Form1: ❑... the Name property for TextBox1 to txtServer ❑ Set the Name property for Label2 to lblDatabase and the Text property to Database 159 Chapter 8 ❑ ❑ Set the Text property for Label3 to Login Name ❑ Set the Name property for TextBox3 to txtLoginName ❑ Set the Text property for Label4 to Password ❑ Set the Name property for TextBox4 to txtPassword and the PasswordChar property to * ❑ Set the Name property... Server or Oracle, depending on which you have available or need to learn Of course, you can work with both if you choose and code the exercises to execute against both databases Before you can work with one of these enterprise relational databases, you need to migrate the data that currently exists in your Microsoft Access database to the database that you’ll be working with In this chapter, you create... dialog box, browse to your Time Tracker project In the Files of Type combo box, select All Files (*) so that you are able to see the app.config file Then select the app.config file and click Add 10 Visual Studio 2005 has made a copy of the app.config file from your Time Tracker project and added it to your DB Migration Utility project You need to modify the section in the app.config file that is for the... and choose Properties from the context menu When the Property Page for the application is displayed, click the Settings tab on the left side You receive a message dialog box informing you that Visual Studio 2005 has added the new values from your app.config file 11 At this point, save your project to have these settings saved Click the Save All button on the toolbar and then click the Save button in... expected in the INSERT statement That is, you add a Parameter that contains the value to be inserted into column1, then the Parameter for column2, followed by the Parameter for column3 INSERT INTO myTable (column1, column2, column3) VALUES(?, ?, ?) You may be wondering why you would want to code a SQL statement in this manner instead of just specifying the values directly in the VALUE clause There are two... executing those INSERT statements against your SQL Server or Oracle database Try It Out Executing SQL Statements with Parameters To complete this exercise: 1 2 Open the DB Migration Utility project in Visual Studio 2005 if it is not already open Switch to the Code Editor for your form and select btnGroups in the Class Name combo box and then select the Click event in the Method Name combo box to add the btnGroups_Click... migrated from Access to SQL Server or Oracle When all of the data has been processed, you see a message indicating that the data was successfully migrated, as shown in Figure 8 -3, which is migrating data to SQL Server Figure 8 -3 171 Chapter 8 6 Now click the Projects button to have the projects data migrated from Access to either SQL Server or Oracle When this data has been migrated you see a message... database errors that they may encounter The first thing accomplished inside the Try block is a call to the InitalizeCommand procedure You examined this procedure in detail in the previous chapter, and basically it initializes the OleDbCommand object with the SQL string and the OleDbConnection object It also sets the CommandType property to a StoredProcedure constant if a query or stored procedure is . GroupName, GroupDescription, LastUpdateDate FROM Groups ORDER BY GroupName; 138 Chapter 7 10_58894x ch07.qxd 10/ 13/ 05 5:52 PM Page 138 The next SELECT query that you build is the usp_SelectGroup query Time Tracker application in Visual Studio 2005 if it is not already open. 2. Switch to the Code Editor for the Admin form and add the following Imports statement: 139 Inserting, Updating, and. statement: 139 Inserting, Updating, and Deleting Data in Access 10_58894x ch07.qxd 10/ 13/ 05 5:52 PM Page 139 Imports System.Data Public Class Admin 3. Now add the following form-level variable declaration: Private

Ngày đăng: 12/08/2014, 10:21

Từ khóa liên quan

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

Tài liệu liên quan