Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Visual Basic 2005 (2006)

.pdf
Скачиваний:
226
Добавлен:
17.08.2013
Размер:
14.97 Mб
Скачать

Chapter 15

Microsoft Access Objects

A Microsoft Access database file, which has an extension of mdb, contains tables, queries, forms, reports, pages, macros, and modules, which are referred to as database objects. That’s a lot of information in one large file, but Microsoft Access manages this data quite nicely. Forms, reports, pages, macros, and modules are generally concerned with letting users work with and display data. You will be writing Visual Basic 2005 applications to do this, so the only database objects you’re really concerned about at the moment are tables and queries.

Tables

A table contains a collection of data, which is represented by one or more columns and one or more rows of data. Columns are typically referred to as fields in Microsoft Access, and the rows are referred to as records. Each field in a table represents an attribute of the data stored in that table. For example, a field named First Name would represent the first name of an employee or customer. This field is an attribute of an employee or customer. A record in a table contains a collection of fields that form a complete set of attributes of one instance of the data stored in that table. For example, suppose a table contains two fields: First Name and Last Name. These two fields in a single record describe the name of that one person. This is illustrated in Figure 15-1.

Figure 15-1

Queries

A query in a database is a group of Structured Query Language (SQL) statements that allow you to retrieve and update data in your tables. Queries can be used to select or update all of the data in one or more tables or to select or update specific data in one or more tables.

Query objects in Microsoft Access are a hybrid of two types of objects in SQL Server: views and stored procedures. Using database query objects can make your Visual Basic 2005 code simpler, because you have fewer complex SQL queries included in your code. They can also make your programs faster, because database engines can compile queries when you create them, whereas the SQL code in a Visual Basic 2005 program needs to be reinterpreted every time it’s used.

To really understand the implications of queries, you need to learn some SQL. Fortunately, compared to other programming languages, SQL is really simple.

476

Accessing Databases

The SQL SELECT Statement

The American National Standards Institute (ANSI) defines the standards for ANSI SQL. Most database engines implement ANSI SQL to some extent and often add some features specific to the given database engine.

The benefits of ANSI SQL are that, once you learn the basic syntax for SQL, you have a solid grounding from which you can code the SQL language in almost any database. All you need to learn is a new interface for the database that you are working in. Many database vendors extended SQL to use advanced features or optimizations for their particular database. It is best to stick with ANSI standard SQL in your coding whenever possible, in case you want to change databases at some point.

The SQL SELECT statement selects data from one or more fields in one or more records and from one or more tables in your database. Note that the SELECT statement only selects data — it does not modify the data in any way.

The simplest allowable SELECT statement is like this:

SELECT * FROM Employees;

This simply means “retrieve every field for every record in the Employees table”. The * indicates “every field.” Employees indicates the table name. Officially, SQL statements in Microsoft Access should end in a semicolon. It usually doesn’t matter if you forget it, as Access will add them automatically.

If you wanted only to retrieve first and last names, you can give a list of field names instead of a *:

SELECT [First Name], [Last Name] FROM Employees;

You need to enclose these field names in square brackets because these field names contain spaces. The square brackets indicate to the SQL interpreter that, even though there is a space in the name, it should treat “First Name” as one object name and “Last Name” as another object name. Otherwise, the interpreter would be unable to follow the syntax.

SQL is a lot like plain English — even a nonprogrammer could probably understand what it means. Now say you wanted to retrieve only the employees whose last name begins with D. To do this, you add a WHERE clause to your SELECT statement:

SELECT [First Name], [Last Name] FROM Employees WHERE [Last Name] LIKE ‘D*’;

A WHERE clause limits the selection of data to only those records that match the criteria in the WHERE clause. The preceding SELECT statement would cause the database to look at the Last Name column and only select those records where the employee’s last name begins with the letter D.

Last, if you want to retrieve these items in a particular order, you can, for example, order the results by first name. You just need to add an ORDER BY clause to the end:

SELECT [First Name], [Last Name] FROM Employees

WHERE [Last Name] LIKE ‘D*’ ORDER BY [First Name];

477

Chapter 15

This means that if you have employees called Angela Dunn, Zebedee Dean, and David Dunstan, you will get the following result:

Angela Dunn

David Dunstan

Zebedee Dean

You’re specifying quite a specific command here, but the syntax is pretty simple — and very similar to how you would describe what you want to an English speaker. Usually, when ordering by a name, you want to order in an ascending order so that A comes first, Z comes last. If you were ordering by a number, though, you might want to have the bigger number at the top — for example, so that a product with the highest price appears first. Doing this is really simple — just add DESC (short for descending) to the ORDER BY clause, which causes the results to be ordered in descending order:

SELECT [First Name], [Last Name] FROM Employees

WHERE [Last Name] LIKE ‘D*’ ORDER BY [First Name] DESC;

The D* means “begins with a D followed by anything.” If you had said *D* it would mean “anything followed by D followed by anything,” basically, “contains D.” This would return the following:

Zebedee Dean

David Dunstan

Angela Dunn

If you want to make it very clear that you want the results in an ascending order, you can add ASC to the ORDER BY clause instead of DESC. But you don’t really need to, since this is the default sort order.

You can summarize this syntax in the following way:

SELECT select-list FROM table-name

[WHERE search-condition]

[ORDER BY order-by-expression [ASC | DESC]]

This means that you must provide a list of fields to include or use a * to select them all. You must provide a table-name. You can choose to provide a search-condition. You can choose to provide an order-by- expression, and if you do, you can make it either ascending or descending.

SQL gets considerably more complicated when you start working with several tables in the same query. But, for various reasons, you don’t need to do this all that much when working with Visual Basic 2005.

Anyway, the best way to get SQL into your head is to practice. Before moving on, please try to answer these questions in your head:

How would you write a query to retrieve the Name, Description, and Price fields from a table called Product?

What would you add to the query to retrieve only items with DVD in their description?

How would you order the results so that the most expensive item comes first?

478

Accessing Databases

Queries in Access

SQL is really a basic programming language, and if you are a programmer who needs to access databases, you will need to use it. However, Microsoft Access provides wizards and visual tools that enable novice programmers to write queries without knowing SQL. Even for SQL programmers, these can sometimes prove useful. These tools, demonstrated in this section, end up producing SQL statements that you can view and modify if you wish, so they can be a good way to learn more about SQL.

Creating a Customer Query

In the next Try It Out section, you use Access to create a simple query that will select customer information from the Customer table in the Northwind.mdb database. You’ll need to ensure that the sample databases were installed when you installed Microsoft Access or Microsoft Office. You’ll create this query and then view the SQL SELECT statement that gets generated by Access.

Try It Out

Creating aCustomer Query

1.Open Microsoft Access and click the Open icon on the toolbar. In the Open dialog box, navigate to C:\Program Files\Microsoft Office\Office11\Samples\ and open Northwind.mdb. Then click the OK button.

The path to Microsoft Office will vary depending on the version you have installed and the installation path chosen at setup.

2.When the database opens, you will see two sections in the navigation bar on the left: Objects and Groups. The Objects section lists all of your database object types, which was discussed in the section on databases. You can also use Groups to gather together related objects of any type, in any way you want (see Figure 15-2).

Figure 15-2

3.Since you want to take a look at how a SQL SELECT statement is built by Access, you need to click the Queries icon under the Objects tab.

479

Chapter 15

4.You are going to build a new query, so double-click “Create query in Design view” in the results window (see Figure 15-3).

Figure 15-3

5.The Show Table dialog box appears and allows you to select one or more tables to be in your query. You only want to select one table: Customers. Click the Customers table and then click the Add button to have this table added to the Query Designer and then click the Close button to close the Show Table dialog box.

6.The Customers table is displayed with all available fields plus an asterisk. You can select the fields that you want to be added to your query, or you can select the asterisk, which will select all fields from the table. For this exercise just select a few fields for your query. Double-click CompanyName in the Customers table to add it to the first column in the grid below the table. The Field and Table cells are automatically filled in. You also want to sort the data by this field, so click in the Sort cell and choose Ascending to have the results of your query sorted by this field. Your screen should now look like Figure 15-4.

Figure 15-4

480

Accessing Databases

7.You now need to add the ContactName field to your grid. Double-click this field in the Customers table and it will be automatically added to the next available column in the grid. Then add ContactTitle in the same way. Your completed query should now look like the one in Figure 15-5.

Figure 15-5

8.Click the Save icon on the toolbar, enter the name CustomerQuery in the Save As dialog box, and then click OK.

9.On the toolbar click the run icon, indicated by !, and you will see results similar to the ones shown in Figure 15-6. Notice that the results are sorted on the CompanyName field in ascending order, as shown in the figure.

Figure 15-6

481

Chapter 15

How It Works

From the choices you made, Access generates a SQL statement. To look at it, you click the View menu and select the SQL View menu item. This will display the SQL statements as shown in Figure 15-7.

Notice that you have the basic SQL SELECT statement followed 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.

Figure 15-7

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 CompanyName field has been specified.

So how does this SQL statement actually get built? Well, 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 on its own is not a valid SQL statement. Once you added the first field and set the sort order for that field, the following SQL statement was generated — which is valid:

SELECT Customer.CompanyName

FROM Customers

ORDER BY Customers.CompanyName;

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.

Let’s move on now and discuss 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, I will discuss the data access components provided in Visual Studio 2005 that assists you in accessing the data in an Access database.

482

Accessing Databases

Data Access Components

There are three main data access components in Visual Basic 2005 that you need for retrieving and viewing data from the database: BindingSource, TableAdapter, and DataSet. The BindingSource and DataSet components 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. Take a brief look at each one of these components in turn.

Figure 15-8

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 will be discussed as a whole in the next chapter.

DataSet

The DataSet component 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 information 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.

Since the DataSet component stores all of the data in memory, you can scroll through the data both forward and backward, and can also make updates to the data in memory. The DataSet component is very powerful, and you will be exploring this 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.

483

Chapter 15

DataGridView

The DataGridView component 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 component 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 DataGridView component, which allow you to customize the appearance of the DataGridView itself through several predefined format styles. You’ll see this later in this chapter.

BindingSource

The BindingSource component acts like a bridge between your data source (DataSet) and your databound controls (that is, controls that are bound to data components). Any interaction with the data from your controls goes through the BindingSource component, 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 component is the component that you will bind to the DataSource property of your controls, as you’ll see later in this chapter.

BindingNavigator

The BindingNavigator component provides a standard UI component that allows you to navigate through the records that are in your data source. It looks very similar to the record navigator shown at the bottom of Figure 15-6.

The BindingNavigator component is bound to your BindingSource component much as the DataGridView component is. When you click the Next button in the BindingNavigator component, it in turn sends a request to the BindingSource component for the next record, and the BindingSource component in turn sends the request to the data source.

TableAdapter

There’s one last component that I want 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 connection 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.

484

Accessing Databases

The TableAdapter will be covered in more detail Chapter 16.

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 2005, 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 component 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.

In this Try It Out, you will be using the data access wizards in Visual Studio 2005 to create the data components necessary to bind data to a DataGridView control. You will be using the Northwind.mdb sample database again as your data source.

Try It Out

Binding Data to a DataGridView Control

1.Create a new Windows Application project called 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 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 will cause the Data Source Configuration Wizard to be displayed.

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 options for a data source.

485