Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 72 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
72
Dung lượng
4,35 MB
Nội dung
470 ❘ CHAPTER 15 ACCESSING DATABASES FIGURE 15-6 How It Works Based on your choices, Access generates a SQL statement. To look at it, click the View ➪ SQL View. This will display the SQL statements as shown in Figure 15-7. FIGURE 15-7 Notice that you have the basic SQL SELECT statement fol- lowed by the field names. Access has prefixed each field name with the table name. Remember that brackets are required only when the field names contain spaces. The table name prefix is actually required only when selecting data from multiple tables where both tables have a field with the same name. However, to reduce the chance of errors, Access has prefixed all fields with the table name. The FROM clause in your SELECT statement specifies the table that data is being selected from (in this case, the Customers table). The ORDER BY clause specifies which fields should be used to sort the data, and in this case the Company field has been specified. How does this SQL statement actually get built? When you first started creating this query you added a table name. Before any fields were added to the grid, Access generated the following SQL statement: SELECT FROM Customers; Of course, this by itself is not a valid SQL statement. When you added the first field and set the sort order for that field, the following SQL statement was generated — which is valid: Data Access Components and Controls ❘ 471 SELECT Customer.Company FROM Customers ORDER BY Customers.Company; As you continued to add fields, the rest of the field names were added to the SQL statement until the complete SQL statement shown in Figure 15-7 was generated. FIGURE 15-8 The next section discusses the basic data access components that are needed in Windows Forms to display data. Since you have been using Microsoft Access in your examples here, the focus is on the data access components provided in Visual Studio 2010 that assist you in accessing the data in an Access database. DATA ACCESS COMPONENTS AND CONTROLS Start by looking at three of the data access components in Visual Basic 2010 that you can use for retrieving and viewing data from the database: Binding- Source, TableAdapter, and DataSet. The BindingSource and DataSet compo- nents are located in the Toolbox under the Data tab, as shown in Figure 15-8. The TableAdapter can be automatically generated depending on the path you take when adding data access components, as you’ll soon discover. The following sections take a brief look at all of these and two new controls. NOTE These components are known as data components and are simply classes, like everything else in the .NET Framework. In this chapter, you will simply see how to use some of them in a Windows application. Data components are discussed as a whole in the next chapter. DataSet The DataSet is a cache of data that is stored in memory. It’s a lot like a mini database engine, but its data exists in memory. You can use it to store data in tables, and using the DataView component (covered in Chapter 16), you can query the data in various ways. The DataSet is very powerful. In addition to storing data in tables, it stores a rich amount of metadata, or ‘‘data about the data.’’ This includes things like table and column names, data types, and the infor- mation needed to manage and undo changes to the data. All of this data is represented in memory in Extensible Markup Language (XML). A DataSet can be saved to an XML file and then loaded back into memory very easily. It can also be passed in XML format over networks, including the Internet. 472 ❘ CHAPTER 15 ACCESSING DATABASES Because the DataSet component stores all of the data in memory, you can scroll through the data both forward and backward, and make updates to the data in memory. You’ll explore the power of the DataSet component in more detail in the next chapter. In this chapter, you will simply be using it to store data and bind it to a control on your form. DataGridView The DataGridView control is a container that allows you to bind data from your data source and have it displayed in a spreadsheet-like format, displaying the columns of data horizontally and the rows of data vertically. The DataGridView also provides many properties that allow you to customize the appearance of the component itself, as well as properties that allow you to customize the column headers and the display of data. More important, though, are the quick links at the bottom of the Properties window for the Data- GridView, which allow you to customize the appearance of the DataGridView itself through several predefined format styles. BindingSource The BindingSource acts like a bridge between your data source (DataSet) and your data-bound controls (that is, controls that are bound to data components). Any interaction with the data from your controls goes through the BindingSource, which in turn communicates with your data source. For example, your DataGridView control will be initially filled with data. When you request that a column be sorted, the DataGridView control will communicate that intention to the BindingSource, which in turn communicates that intention to the data source. The BindingSource is the component that you will bind to the DataSource property of your controls. BindingNavigator The BindingNavigator control provides a standard UI that enables you to navigate through the records in your data source. It looks very similar to the record navigator shown at the bottom of Figure 15-6. The BindingNavigator control is bound to your BindingSource component much like the DataGridView control is. When you click the Next button in the BindingNavigator, it in turn sends a request to the BindingSource for the next record, and the BindingSource in turn sends the request to the data source. TableAdapter There’s one last component to talk about: the TableAdapter. This component does not reside in the Toolbox but can be automatically generated for you depending on how you add your data access components to your project. The TableAdapter contains the query that is used to select data from your database, as well as con- nection information for connecting to your database. It also contains methods that will fill the DataSet in your project with data from the database. You can also choose to have the TableAdapter generate INSERT , UPDATE ,and DELETE statements based on the query that is used to select data. The TableAdapter is covered in more detail in Chapter 17. Data Binding ❘ 473 DATA BINDING Data binding means taking data referenced by your BindingSource and binding it to a control. In other words, the control will receive its data from your data access components, and the data will be automatically displayed in the control for the user to see and manipulate. In Visual Basic 2010, most controls support some level of data binding. Some are specifically designed for it, such as the DataGridView and TextBox. In your next Try It Out, you will be binding data from a BindingSource to a DataGridView control, so this is where you want to focus your attention. Later in this chapter you’ll bind data to a TextBox control. TRY IT OUT Binding Data to a DataGridView Control Code file Northwind Customers DataGridView.zip available for download at Wrox.com In this Try It Out, you will be using the data access wizards in Visual Studio 2010 to create the data objects necessary to bind data to a DataGridView control. You will be using the Northwind sample database again as your data source. 1. Create a new Windows Forms Application project named Northwind Customers DataGridView. 2. Click the Data tab in the Toolbox and then drag a DataGridView control from the toolbox and drop it on your form. The DataGridView control will display the DataGridView Tasks dialog box, as shown in Figure 15-9. FIGURE 15-9 3. Click the drop-down arrow in the Choose Data Source combo box and then click the Add Project Data Source link at the bottom of the list that is displayed. This displays the Data Source Configu- ration Wizard. 4. The Choose a Data Source Type screen allows you to choose the data source for your data. As you can see from this screen, shown in Figure 15-10, you have several data source options. You can click the Database icon for connecting to various databases such as SQL Server, Oracle, and 474 ❘ CHAPTER 15 ACCESSING DATABASES Access; the Web Service icon for connecting to a web service; or the Object icon for connecting to your business logic components. Click the Database icon and then click the Next button. FIGURE 15-10 5. The next screen is for Database Model. The Choose Dataset and click Next. In the Choose Your Data Connection screen, click the New Connection button. 6. In the Choose Data Source dialog box, select Microsoft Access Database File in the Data Source list and then click the Continue button. 7. In the Add Connection dialog box, click the Browse button and navigate to the samples folder for Microsoft office. For 2007, the database is where you downloaded it. By default, it would be in your document library. In Access 2003, it should be in the folder C:\Program Files\Microsoft Office\Office11\Samples\ for a default installation of Microsoft Office 2003 (11 is the version and will change based on your version of Office). 8. Select the Northwind database in the Select Microsoft Access Database File dialog box and click the Open button to have the path and filename added to the text field on the Add Connection dia- log box. You can click the Test Connection button to verify your choices. Click the OK button when you are done to close the Add Connection dialog box and then click the Next button on the Choose Your Data Connection screen. 9. The next dialog is for the connection. If you made no changes to your database, accept the default settings. Test your connection with the Test Connection button to ensure it is correct and click OK. 10. Now you are back to the first screen. Click Next to continue. You will be prompted with a dialog box that informs you that the data file is not part of your project and asks if you want to add it. Click the Yes button in this dialog box. Data Binding ❘ 475 11. Click the Next button on the Save the Connection String to the Application Configuration File screen. 12. The Choose Your Database Objects screen allows you to select the data that your application needs. Here you have the option to select data directly from the tables in your database, data generated from the execution of various views and stored procedures, or data generated from the execution of functions. 13. You’ll be using the query that you created in the last Try It Out exercise, so expand the Views node in the Database objects list and then select the check box for CustomerQuery as shown in Figure 15-11. If you expand CustomerQuery, you’ll see the columns that are returned from this query. Click the Finish button when you are done. At this point, the wizard will generate a DataSet named Northwind_2007DataSet , a Binding- Source named CustomerQueryBindingSource , and a TableAdapter named CustomerQuery- TableAdapter . FIGURE 15-11 14. Because you will not be adding, editing, or deleting records from this table, uncheck the check box next to these options in the DataGridView Tasks dialog box. If you don’t see this, click on Data- GridView and an arrow will appear at the top right. Click this arrow and you will see the DataGridView Tasks dialog box. You will, however, want to implement sorting in your Data- GridView control, so check the check box next to Enable Column Reordering. When you are done, click the title bar of the form to hide the dialog. 15. Click the DataGridView control and, in the Properties window, set the Dock property to Fill. 16. At this point you can run your project to see the results. Click the Start button on the toolbar. Your form will be displayed with the DataGridView control populated with data. 476 ❘ CHAPTER 15 ACCESSING DATABASES You can click the column headers to have the data in the DataGridView sorted in ascending order. Clicking the same column header again will sort the data in descending order. Each sort order will be indicated with an arrow pointing up for ascending and down for descending. How It Works At this point you have not written a single line of code to achieve these results, which just goes to prove how powerful the data wizards in Visual Basic 2010 are. The preceding approach for this example is the easiest and most straightforward approach for data access. You start by adding a DataGridView control to your form, which prompts you with the Tasks dialog box for the DataGridView. This dialog box allows you to create a new Data Source via the Data Source Configuration Wizard, which walks you through a series of steps. First, you identify the type of data source that you wanted to use. Then you specify the type of database object that you want to use to retrieve your data; in this step you merely chose to use a specific table in your database and select specific columns from that table. When you click the Finish button, several components are automatically generated and added to your project. These include the TableAdapter, DataSet, and BindingSource. The BindingSource is bound to the DataSource property of the DataGridView control. Remember that the BindingSource’s job is to communicate the data needs of the control to the data source, which in this case is the DataSet containing all of the data. The DataSet is populated with data by the TableAdapter when your form is loaded. The most important point of this exercise is to show the ease with which you are able to create a data- bound application and the simple fact that you do not have to write a single line of code to achieve the end results. TRY IT OUT Binding Data to TextBox Controls Code file Northwind Customers BindingNavigator.zip available for download at Wrox.com In this Try It Out exercise, you’ll be using several TextBox controls on your form, binding each text box to a certain field in your BindingSource. You’ll then use a BindingNavigator control to navigate through the records in your DataSet. 1. Create a new Windows Forms Application project named Northwind Customers BindingNavigator. FIGURE 15-12 figure 2. Add three Label controls and three TextBox controls to your form. Arrange the controls so that your form looks similar to Figure 15-12, and set the Text properties of the Label controls. 3. Click the first text box on your form and then expand the (DataBindings) property in the Properties window by click- ing the plus sign next to it. Then click the Text property Data Binding ❘ 477 under the DataBindings property. Now click the drop-down arrow for the Text property. At this point you’ll see the Data Source window shown in Figure 15-13. Click the Add Project Data Source link to invoke the Data Source Configuration Wizard, which you saw in the previous Try It Out exercise. FIGURE 15-13 figure 4. Select the Database icon in the Choose a Data Source Type screen and click the Next button. In the Database Model dia- log, choose DataSet and click Next. 5. In the Choose Your Data Connection screen, click the New Connection button. 6. In the Add Connection dialog box, click the Browse button and navigate to where the Northwind database is located. This is the same location as the previous example. Select the Northwind database in the Select Microsoft Access Database File dialog box and click the Open button to have the path and filename added to the text field on the Add Connection dialog box. Test the connection and click the OK button when you are done to close the Add Connection dialog box, and then click the Next button on the Choose Your Data Connection screen. You will be prompted with a dialog box that informs you that the data file is not part of your project and asks if you want to add it. Click the Yes button in this dialog box. 7. Click the Next button on the Save the Connection String to the Application Configuration File screen. 8. In the Choose Your Database Objects screen, expand the Tables node in the Database objects list and then expand the Customers table. Select the check box for First Name, Last Name, and Job Title. Click Finish. FIGURE 15-14 figure 9. Click the drop-down arrow next to the Text property in the Proper- ties window. At this point, you’ll see the Data Source window shown in Figure 15-14. Expand the Other Data Sources node, the Project Data Sources node, the Northwind_2007DataSet node, and finally the Customers node. Now click the First Name field. The window will close, and the Text field under the DataBindings property will be bound to the First Name field in your DataSet. If you look at the bottom of the IDE, you’ll notice that a North- wind_2007DataSet, CustomersBindingSource, and Customers- TableAdapter have been automatically generated. 10. Click the second text box on your form, and then select the Text property under the DataBindings property in the Properties window. Now click the drop-down arrow for the Text property. Expand the CustomersBindingSource node in the Data Source window, and then click the Last Name field. 478 ❘ CHAPTER 15 ACCESSING DATABASES NOTE This is not exactly what you did in step 9. Be sure to click CustomersBindingSource or you will have a new Binding Source added to your project and the text boxes will change together. 11. Click the third text box on your form, and then click the Text property under the DataBindings property in the Properties window. Click the drop-down arrow for the Text property, expand the CustomersBindingSource node in the Data Source window, and then click the Job Title field. 12. Return to the Toolbox, drag a BindingNavigator control from the Data tab, and drop it on your form. The BindingNavigator control will be automatically docked to the top of the form. FIGURE 15-15 figure 13. In the Properties window, locate the BindingSource property, and then click that field. Now click the drop-down arrow for the BindingSource property and choose CustomersBinding- Source from the list. 14. Finally, click the Start button on the toolbar to run your project. Your form that is displayed should look similar to the one shown in Figure 15-15. You’ll be able to navigate through the records in your data source, navigating backward and for- ward as well as being able to go the first and last record. NOTE Clicking the Delete button will delete records from your DataSet but will not delete records from the database. Likewise, clicking the Add button will add an empty record to your DataSet but not to the database. You would need to write some code to actually have the database updated with the changes from your DataSet. How It Works The beauty of using the BindingNavigator control is that you’ve quickly built a form that will navigate through the records of your database without you having to write a single line of code. In this example, you added three Label and TextBox controls to your form. You then set the DataBindings properties of the text boxes. When you set the Text DataBindings property of the first text box, you are prompted to add a new data source, which again invokes the Data Source Configuration Wizard. You use the Data Source Configuration Wizard in this exercise in the same manner as you did in the previous exercise. When you complete the Data Source Configuration Wizard, it automatically generates a TableAdapter, DataSet, and BindingSource. You are then able to choose which field in the DataSet to bind to the DataBindings Text property. Summary ❘ 479 When you add the BindingNavigator control to your form, setting it up is a matter of simply choosing the BindingSource that is generated by the Data Source Configuration Wizard in the BindingSource property in the Properties window. Again, this exercise has demonstrated the simplicity with which you can create data-bound applications without the need to write any code. SUMMARY You started this chapter by exploring what a database actually is and then looked at the SQL SELECT statement. You put this knowledge to use by creating a query in the Northwind.mdb database to see the SQL statements that Access generated for you. You then took a look at the basics of binding data to controls on a form, specifically the DataGridView control and TextBox controls. You have examined the necessary basic data access components required to retrieve data from an Access database and bind that data to your controls. You used the components and controls provided in the Data tab of the Toolbox for your data access, and used the wizards to generate the necessary code to connect to the database and retrieve the data. After working through this chapter, you should know: ➤ What a database is and the basic objects that make up a database ➤ How to use the SQL SELECT statement to select data from a database ➤ How to use the Data Source Configuration Wizard to create the data access components needed to perform data binding ➤ HowtobinddatatoaDataGridViewcontrol ➤ How to bind data to TextBox controls and use the BindingNavigator control You have seen that the wizards provided in Visual Studio 2010 make it simple to bind data quickly to the controls on a form. Sometimes, however, you need more control over how you interact with the data in a database and how you bind the data to the controls on a form. Chapter 16 takes a different approach to data binding by programmatically binding data to controls on a form. You will also be exploring the data access components in more detail and will learn how to set their properties and execute their methods from your code. EXERCISES 1. How would you write a query to retrieve the Name , Description ,and Price fields from a table called Product ? 2. What would you add to the query to retrieve only items with DVD in their description? [...]... installed with Visual Studio The chapter is based on SQL Server 20 08 but the code should work with SQL Server 2005 with only minor adjustments, if any As a beginner, it will be easier for you to use SQL Server 20 08 without the worry of minor changes The database can reside in SQL Server 20 08 on your local machine or in SQL Server on a network This chapter has examples of SQL Server 20 08 Express running... following resources: ➤ SQL Server 2000 scripts and instructions can be downloaded from www .microsoft. com/ downloads/details.aspx?FamilyID=06616212-0356-46A0-8DA2-EEBC53A 680 34 This script will work with 20 08 versions This is the easiest place to get the database ➤ If the links are a hassle to type, just go to www .microsoft. com/downloads and search for SQL Server Sample Databases The search results will... 20 08 Express running locally The database the examples use is the pubs database from Microsoft You can download SQL Server 20 08 Express, without cost, from www .microsoft. com/sql and choose the link for users who already have SQL Server installed The Web Platform Installer will not allow you to install another instance and Visual Studio installs one for you Select the version with tools You can also enter... 480 ❘ CHAPTER 15 ACCESSING DATABASES 3 How would you order the results so that the most expensive item comes first? 4 What do you put around column names that have spaces in them? 5 In Visual Studio 2010, what control can you use to navigate through data in a Windows Forms Application? 6 What is the... "(au_id, au_lname, au_fname, contract) " & _ "VALUES(’123-45-6 789 ’, ‘Barnes’, ‘David’, 1)" The INSERT statement is a very simple one that means ‘‘Insert a new row into the authors table In the au_id column put ‘123-45-6 789 ’, in the au_lname column put ‘Barnes’, in the au_fname column put ‘David’, and in the contract column put ‘1’.’’ This is the basic way that INSERT statements work in SQL You have INSERT... SqlCommand object The term parameters here refers to the parameters required to provide data to your SQL statement or stored procedure, not to the parameters that are required to be passed to a Visual Basic 2010 method You can access the Parameters collection of the SqlCommand object by specifying the Parameters property After you access the Parameters collection, you can use its properties and methods... own copy 484 ❘ CHAPTER 16 DATABASE PROGRAMMING WITH SQL SERVER AND ADO.NET You will also learn how to access SQL Server databases using the SqlClient data provider As mentioned in the previous chapter, SqlClient is significantly faster than OleDb, but it works only with SQL Server databases To complete the exercises in this chapter, you need to have access to a version of SQL Server 20 08 One is installed... use in accordance with the Wrox Terms of Service and under US copyright as stated on this book’s copyright page If you did not purchase this copy/ please visit www.wrox.com to purchase your own copy 488 ❘ CHAPTER 16 DATABASE PROGRAMMING WITH SQL SERVER AND ADO.NET connection to the database specified in the connection string An example of this is shown in the following code fragment: ‘ Open the database... installs one for you Select the version with tools You can also enter the following URL directly: blogs.msdn.com/ sqlexpress/archive/2009/06/15/installing-sql-server-20 08- guidance.aspx Here are some notes for installing SQL Server 20 08 Express (Runtime with Management Tools): ➤ For Chapter 16, you should install a named instance of SQLEXPRESS to avoid having to customize the code ➤ Chapter 16 uses mixed... Server For production, create a login that has a few rights as possible to use or use windows authentication where you can give rights to users or groups ➤ To run SQL Server 20 08 on Windows 7 you have to install SQL Server 20 08 Service Patch 1 or later ➤ Select to install the database engine ➤ Be sure to select mixed mode authentication The sa account will not be active unless mixed mode authentication . in Visual Studio 2010 that assist you in accessing the data in an Access database. DATA ACCESS COMPONENTS AND CONTROLS Start by looking at three of the data access components in Visual Basic 2010 that. instructions can be downloaded from www .microsoft. com/ downloads/details.aspx?FamilyID=06616212-0356-46A0-8DA2-EEBC53A 680 34 .Thisscript will work with 20 08 versions. This is the easiest place to. data will be automatically displayed in the control for the user to see and manipulate. In Visual Basic 2010, most controls support some level of data binding. Some are specifically designed for