Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

878 Chapter 20 DATABASES: ARCHITECTURE AND BASIC CONCEPTS

The Database Designer and Tables Designer These tools allow you to work with an entire database or its tables. When you work with the database, you can add new tables, establish relationships between the tables, and so on. When you work with individual tables, you can manipulate the structure of the tables, edit their data, and add constraints. You can use these tools to manipulate a very complicated object—the database—and its components with point-and-click operations.

The Server Explorer

Your starting point for developing database applications with VB.NET is the Server Explorer. This toolbox is your gateway to the databases on your system or network, and you can use it to locate and retrieve the tables you’re interested in. Place the pointer over the Server Explorer tab to expand the corresponding toolbox, which looks something like the one shown in Figure 20.5. The two main objects in the Server Explorer are Data Connections and the Servers object. Under the Data Connections branch, you will see the connections to databases you’re programming against. Under the Servers branch, you will see the database servers you can access from your computer and various objects they expose.

Figure 20.5

The Server Explorer contains the database objects you can access on your computer.

Note Note that the Server Explorer’s tools are available even if no project is open at the time. These tools allow you to work with the objects of a database, and the actions you’ll perform (like the design of a table) are not specific to a project.

Right-click the Data Connections icon and, from the context menu, select the Add Connection command. You may also see one or more connections to your databases, if you have already created some. Every new connection you add remains under the Data Connections branch until you decide to remove it, and you can use it in any number of projects.

To add a new connection, select the Add Connection command and the Data Link Properties dialog box will pop up, as shown in Figure 20.6. In the Data Link Properties dialog box, specify a new connection to one of the databases on your system. First, you must select the database provider

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE SERVER EXPLORER 879

(basically, the driver you’ll use to access the database). For the examples of this part of the book, I will use SQL Server databases.

Figure 20.6

The Provider and Connection tabs of the Data Link Properties window

Then switch to the Connection tab. Here you must enter the User Name and Password in the appropriate boxes. If you (or the administrator) have set up SQL Server to use the Windows NT integrated security, just check the radio button named Use Windows NT Integrated Security. Then drop down the top list box to select one of the SQL Servers your computer can access. You will see the local SQL Server, as well as any other SQL Server on the network. Select the local SQL Server, then select the Northwind database in the second drop-down list on the dialog box. If SQL Server is running on the same computer as Visual Studio, you won’t see the names of the servers, but the local one is selected by default.

If you have Access 2000 installed on your system, use the Microsoft Jet 4.0 OLE DB Provider. On the Connection tab, click the Test Connection button to make sure you can connect to the database. If not, make sure SQL Server is running and that the user name and password you specified are correct.

Click OK to close the Data Link Properties dialog box, and the name of the new connection will appear under the Data Connections branch of the tree in the Server Explorer window. The default name of the connection is made up of the name of the computer followed by the name of the data- base—for my server, PowerToolkit.Northwind—but you can change it. Right-click a connection and, from the context menu, select Rename.

Switch back to Server Explorer tab and expand the new connection. You will see the following entries under it:

Database Diagrams This is where you can examine the various diagrams of the database. A database diagram is a visual representation of a set of related tables, with the relations between the tables. Relations are indicated with line segments between two related tables, and you can quickly learn a lot about the structure of a database by looking at a database diagram.

Tables This is where you can select a table and edit it, or add a new table to the database. You can edit the table itself (change its design by adding/removing rows or change the data types of

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

880 Chapter 20 DATABASES: ARCHITECTURE AND BASIC CONCEPTS

one or more columns). Finally, you can view the table’s rows and edit them, add new rows, or delete existing rows.

Views This is where you specify the various views you want to use in your applications. Sometimes, the tables are not the most convenient, or even the most expedient, method of looking at your data. If the database contains a table with employees and this table includes wages or other sensitive data, you can create a view that’s identical to the table but excludes selected columns.

Views are created with SQL SELECT statements, which are discussed in detail later in this chapter. A SELECT statement basically allows you to specify the information you want to retrieve from the database. This information can be stored in a View object, which is just like another table to your application.

Stored Procedures Stored procedures are (usually small) programs that are stored in the database and perform very specific, and often repeated, tasks. By coding many of the operations you want to perform against the database as stored procedures, you won’t have to access the database directly. Moreover, you can call the same stored procedure from several places in your VB code, and you can be sure that the same action is performed every time. Once created, the stored procedure becomes part of the database, and programmers (as well as users) can call it by name, passing the appropriate arguments if necessary. A typical example is a stored procedure for removing orders. The stored procedure must remove the order details first, then remove the order (and possibly update the customer’s balance, the stock, and so on). In general, orders shouldn’t be removed from a database—they should be cancelled with another transaction—but with the fake orders people place to online stores, many developers allow the removal of orders.

Functions The functions of SQL Server are just like the VB functions. They perform specific tasks on the database (retrieve or update data) taking into consideration the arguments passed to the functions when they were called. ADO.NET is built around SQL statements and stored procedures, so we’re not going to discuss SQL Server functions in this book.

Working with Tables

Expand the Tables tree to see the list of tables in the Northwind database. If you right-click one of them, you will see the following (among other trivial options).

Retrieve Data from Table

This command brings the entire table onto a grid. You can edit any row and even delete rows or add new ones. Figure 20.7 shows the data of the Customers table of the Northwind database in edit mode.

To experiment with tables, open the Categories table by double-clicking its name. Select a row by clicking the gray button in front of the row and then click the Delete button. First, you’ll be warned that you’re about to remove a row and that the action can’t be undone. If you click Yes, the row should be removed. If you attempt to remove a row from the Categories table, however, you’ll get the following warning:

DELETE statement conflicted with COLUMN REFERENCE constraint ‘FK_Products_Categories’. The conflict occurred in database ‘Northwind’, table ‘Products’, column ‘CategoryID’.

The statement has been terminated

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE SERVER EXPLORER 881

Figure 20.7

Editing the Customers table in Visual Basic’s IDE

This simply means that there’s a constraint in the database that will be violated if you remove this line. The constraint is between the Products and Categories tables. Each product belongs to a category, and if you remove this category, some of the products will be left without a category. Notice that this restriction is added to the database when it was designed—it’s not SQL Server’s idea to protect you from such mistakes. The designers of the Northwind database added the appropriate constraints, so that users won’t violate the integrity of the database accidentally. As you will see, it’s easy to add new constraints to a table and to protect the integrity of the database from mistakes of programmers and users alike.

If you attempt to delete a row from the Products table, you’ll get a similar error, but this time the conflict is between the Products and Order Details tables. Each row in the Order Details table contains a product’s ID, and if you were allowed to remove a product from the Products table, some invoices would reference nonexistent products.

However, you can delete rows from the Order Details table. Just write down the fields of the row you’re deleting, so that you can add it later. You don’t have to add the deleted row, but be aware that some of the queries in the following sections and chapters may not return the exact same rows as shown in this book. To delete a row, select it by clicking the gray button in the first column of the grid and then tap the Delete key.

To add a row, press Ctrl+End to go to the last line, place the cursor in the first cell of the row marked with an asterisk (this is the new row), and start typing. To move to the next cell, press Tab. To commit the new row to the database, move the pointer to another row. As long as you’re editing a row, the icon with the pen appears in the first column of the grid. While this icon is displayed, the original row in the table hasn’t changed yet. After you’re done entering values, move the pointer to another row and the icon of the pen will disappear, indicating that the row has been successfully added. If the data are not consistent with the structure of the database, the changes will be aborted by the database. If you attempt to enter a new product with a CategoryID that doesn’t exist in the Categories table, the new row will not be accepted. Likewise, if you attempt to create a new order for a nonexistent customer, the new row will also be rejected.

Design Table

Close the table, return to the Server Explorer, right-click one of the tables, and this time select Design Table. The table’s structure will appear on a grid, as shown in Figure 20.8. The first column contains the table’s column names (the fields of each row).

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

882 Chapter 20 DATABASES: ARCHITECTURE AND BASIC CONCEPTS

Figure 20.8

The Customers table in design view

Each column has a name, a data type, and a length. To set the data type of a column, click the Date Type cell of a field. This cell is a ComboBox displaying all available data types. Drop down the list of data types and select the desired one. The most common data types are the char and varchar types, which store strings, and the numeric types, including the money data type. There’s also a special field for storing dates and times. Basically, you can use all the data types available in VB and a few more data types that are unique to SQL Server. The difference between the char and varchar data types is that the char type stores strings of fixed length (the length is specified by the value in parentheses following the data type’s name) and the varchar type stored strings of variable length. The value in parentheses is the maximum allowed length of the string for variable-length strings.

You can also set the Allow Nulls field to indicate whether a field may have no value. The Null value is a very special value in database programming. It’s not the numeric zero and it’s not an empty string. Null means that the field has no value. Thus, it can’t be used in comparisons and you can’t read its value. In the Customers table, for instance, neither the CustomerID nor the CompanyName fields may be Null. Any other field may be Null. When we enter a new customer, we may not know the address or the phone number. But we have to assign an ID to the customer that will make the new row unique in the entire table, and we must also specify the company’s name.

The Northwind database uses five-letter keys to identify each customer. This is rather unusual, because we don’t want to burden the user with the task of coming up with unique keys for each customer. This task can be left to the database, which is capable of providing a unique numeric value to each new row added to the table. Of course, the autogenerated fields are integers, but they’re just as good (if not better). They uniquely identify a row in the table, and they’re used to relate the rows of one table to the rows of another. Normally, user never look up customers by their ID.

In the lower section of the window, you see additional information about the selected field. Each field has a Description, a Default Value, and a Collation setting (the last setting applies to character fields only). The Description field holds information that will help programmers figure out the role of each field and is supplied by the database designer. The Default Value is a value that will be placed in this field automatically when a new row is added to the table. If most of the customers are

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com