applica-❑ Chapter 1 provides an overview of the components that make up Access, SQL Server, andOracle databases as well as a refresher on relational database design and normalization.. I
Trang 2Beginning Visual Basic® 2005 Databases
Trang 4Beginning Visual Basic® 2005 Databases
Thearon Willis
Trang 5Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CON-TENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUTLIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE NO WARRANTY MAY BE CRE-ATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS THE ADVICE AND STRATEGIES CON-TAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK IS SOLD WITH THEUNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OROTHER PROFESSIONAL SERVICES IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF ACOMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THEAUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM THE FACT THAT AN ORGANIZATION
REP-OR WEBSITE IS REFERRED TO IN THIS WREP-ORK AS A CITATION AND/REP-OR A POTENTIAL SOURCE OF THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR-MATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE.FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVECHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.For general information on our other products and services please contact our Customer Care Department withinthe United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002
FUR-Trademarks:Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress aretrademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the United States and othercountries, and may not be used without written permission Visual Basic is a registered trademark of MicrosoftCorporation in the United States and/or other countries All other trademarks are the property of their respectiveowners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book
Trang 6About the Author
Thearon Willisis a senior consultant with over 20 years of programming experience He started writingapplications using the Basic language in 1980 and later moved on to Visual Basic and finally to VisualBasic.Net He began working with databases in 1987 and has been hooked on writing database applica-tions ever since He has experience with SQL Server, Oracle, and DB2 but works with SQL Server on adaily basis Thearon has programmed in several other languages, some of which include C++, Assembler,Pascal, and COBOL However, he enjoys Visual Basic.Net the best as it provides the features needed toquickly build Windows and Web applications as well as components and Web Services He currentlydevelops intranet applications, Web Services, and server-side and client-side utilities using VisualBasic.Net Most of these applications and utilities are database-driven and make use of XML and XSL
Thearon lives with his wife, Margie, and daughter, Stephanie, in the Raleigh, North Carolina area
Trang 8Mary Beth Wakefield
Vice President & Executive Group Publisher
Richard Swadley
Vice President and Publisher
Joseph B Wikert
Proofreading and Indexing
TECHBOOKS Production Services
Trang 10For my dearest love
Trang 12Acknowledgments xvii Introduction xix
Trang 13Chapter 3: Visual Studio 2005 Data Wizards 47
Trang 14Chapter 6: Selecting Data in Access 107
Summary 121 Exercises 121
Trang 15Chapter 10: Building Business Logic and Data Access Components 235
Summary 298
Validating Data in the Business
Summary 434 Exercises 435
Trang 16Chapter 13: Updating Data 437
Summary 478 Exercises 479
Summary 530
Summary 568
Referencing a Web Service in a Windows Application 571 Referencing a Web Service in a Web Application 580 Summary 601
Trang 18As always, I want to thank my wife, Margie, and my daughter, Stephanie, for the patience they haveshown while I write another book Without their love and support, none of this would be possible
Trang 20This book teaches Visual Basic 2005 developers the concepts and skills necessary to write VB 2005database applications that can be used throughout their enterprises Although the book touches ondatabase design concepts, its focus is on using ADO.NET to access and manipulate data in relationaldatabases This book covers all data providers in ADO.NET briefly, but focuses on using the OleDb DataProvider for accessing Access databases, the SQL Data Provider for accessing SQL Server databases, andthe Oracle Data Provider for accessing Oracle databases Most of the examples in this book involve writ-ing database applications for SQL Server and Oracle
You will learn how to use queries, views, and stored procedures to efficiently access and manipulatedata from your applications I provide examples and instruction on accessing data from Windows appli-cations, ASP.NET applications, and Web Services You’ll also be exposed to more advanced concepts,such as writing business logic components and data access components, as well as how to read andwrite data from the Windows Registry You will also learn how to encrypt and decrypt data using the.NET encryption classes and how to hash passwords to further secure your access to your data
Who Is This Book For
This book was designed for the developer who wants to learn how to write database applications usingVisual Basic 2005 and back-end databases such as Microsoft Access, Microsoft SQL Server, and Oracle
There are two kinds of developers for whom this book is ideal:
❑ The beginning VB 2005 developer who already has some experience with Visual Basic 2005 oping Windows and ASP.NET applications You’ve read Beginning VB 2005 and are ready to
devel-learn database programming using VB 2005 Congratulations, you’ve made a great choice andwill learn the skills and concepts necessary to write efficient database applications
❑ The experienced VB 2005 developer who is new to database programming You’ve also made a
great choice, as you will hone your VB 2005 skills while you learn the skills and concepts sary to write efficient database applications
neces-What This Book Covers
The ADO.NET classes offer a lot of features and functionality, much more than one book can cover indetail This is especially true given all of the overloaded operators and methods available in theseclasses However, the goal of this book is to teach you the concepts for efficiently accessing and manipu-lating data in enterprise applications A brief review of database design concepts will help you under-stand relational database design
Trang 21ADO.NET is covered thoroughly so that you can get a firm grasp on this important data access ogy in the NET Framework Hands-on examples and Try It Out exercises are provided to help you putinto practice the topics that you read about
technol-This book is not intended to be used as a reference but as a teaching tool on building database tions using Visual Basic 2005 To that end, this book walks you through the process of building the vari-ous pieces of a single application chapter by chapter
applica-❑ Chapter 1 provides an overview of the components that make up Access, SQL Server, andOracle databases as well as a refresher on relational database design and normalization
❑ Chapters 2 and 3 provide an overview of ADO.NET and the data wizards available in VisualStudio 2005
❑ Chapters 4 through 7 give you hands-on experience writing queries in Access and executingAccess queries in your VB 2005 applications
❑ Chapters 8 through 13 give you hands-on experience writing stored procedures and views inboth SQL Server and Oracle, and executing those stored procedures and views from your VB
2005 application You also build and enhance a business logic component and data access ponent starting in Chapter 10
com-❑ Chapter 14 shows you how to use your business logic and data access components in anASP.NET application to display and update data in your back-end databases
❑ Chapter 15 shows you how to create a Web Service that also uses your business logic and dataaccess components to produce report data
❑ Finally, Chapter 16 shows you how to access your Web Service from both a Windows and Webapplication
What You Need to Run the Examples
The following list describes the software components that you will need to complete the Try It Out cises in each chapter
exer-❑ All chapters:Visual Studio 2005 Standard, Professional or Team System edition
❑ Chapters 3 through 8:Microsoft Office (2000, XP, or 2003 editions) or Microsoft Access
(2000, XP, or 2003 editions)
❑ Chapter 3 and Chapters 8 through 16:You will need access to SQL Server 2005 or Oracle 10ginstalled locally on your machine or on your network
Conventions
This book uses several different styles of text and layout to help differentiate between the different kinds
of information Here are examples of the styles used and an explanation of what they mean
Trang 22Try It Out How Do They Work?
1. Each step has a number.
2. Follow the steps
3. Then read the How It Works section that follows to find out what’s going on
These notes hold important, not-to-be-forgotten, mission-critical details that are directly relevant to the surrounding text.
Bullets appear indented, with each new bullet marked as follows:
❑ Important words are in italics.
❑ Text you are required to type is in bold.
Code has several styles If I am talking about a word in the text—for example, when discussing a
For Nextloop—it’s in this font If it’s a block of code that can be typed as a program and run, thenit’s also in a gray box:
Private Sub mnuHelpAbout_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles mnuHelpAbout.ClickDim objAbout As New About
objAbout.ShowDialog(Me)objAbout = NothingEnd Sub
Sometimes you’ll see code in a mixture of styles, like this:
Private Sub mnuHelpAbout_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles mnuHelpAbout.ClickDim objAbout As New About
objAbout.ShowDialog(Me)objAbout.Dispose()objAbout = NothingEnd Sub
In cases like this, the code with a white background is code you are already familiar with; the line lighted in gray is a new addition to the code since you last looked at it
high-Customer Suppor t
We always value hearing from our readers, and we want to know what you think about this book: what you liked, what you didn’t like, and what you think we can do better next time You can send us your comments either by returning the reply card in the back of the book or by e-mail to
feedback@wrox.com Please be sure to mention the book title in your message
Trang 23How to download the sample code for the book
When you visit the Wrox site (wrox.com) simply locate the title through our Search facility or by clickingthe Download Code link at the top of the main page; then find the book in the title list Click the HTTP
or FTP link for the book to download the code
The files that are available for download from our site have been archived using WinZip When youhave saved the attachments to a folder on your hard drive, you need to extract the files using a decom-pression program such as WinZip or PKUnzip When you extract the files, the code is usually extractedinto chapter folders When you start the extraction process, ensure that your software (WinZip orPKUnzip) is set to use folder names
Errata
We’ve made every effort to ensure that there are no errors in the text or in the code However, no one isperfect and mistakes do occur If you find an error in one of our books, such as a spelling mistake or afaulty piece of code, we would be very grateful for feedback By sending in errata, you may save anotherreader hours of frustration, and, of course, you will be helping us provide even higher quality informa-tion Simply e-mail the information to support@wrox.com; your information will be checked and, if cor-rect, posted to the errata page for that title, or used in subsequent editions of the book
To find errata on the Web site, go to wrox.comand simply locate the title through our Advanced Search
or title list or by going to the Help Center using the link at the bottom of the main page Click the ViewErrata link, which is to the right of the book’s title
E-mail support
If you wish to directly query a problem in the book with an expert who knows the book in detail, thene-mail support@wrox.comwith the title of the book and the last four numbers of the ISBN in the subjectfield of the e-mail A typical e-mail should include the following things:
❑ The title of the book, the last four digits of the ISBN (894X), and the page number of the problem
in the Subject field
❑ Your name, contact information, and the problem in the body of the message
We won’t send you junk mail We need the details to save your time and ours When you send an e-mailmessage, it will go through the following chain of support:
❑ Customer support:Your message is delivered to our customer support staff, who are the firstpeople to read it They have files on most frequently asked questions and will answer anythinggeneral about the book or the Web site immediately
❑ Editorial:Deeper queries are forwarded to the technical editor responsible for that book Theyhave experience with the programming language or particular product, and are able to answerdetailed technical questions on the subject
❑ The authors:Finally, in the unlikely event that the editors cannot answer your problem, theywill forward the request to the author We do try to protect authors from any distractions totheir writing; however, we are quite happy to forward specific requests to them All Wroxauthors help with the support on their books They will e-mail the customer and the editor with
Trang 24The Wrox support process can offer support only for issues that are directly pertinent to the content ofour published title Support for questions that fall outside the normal scope of a book’s support is pro-vided via the community lists of our http://p2p.wrox.com/forum.
p2p.wrox.com
For author and peer discussion, join the P2P forums Our unique system provides programmer contact on mailing lists, forums, and newsgroups, all in addition to our one-to-one e-mailsupport system If you post a query to P2P, you can be confident that it is being examined by the manyWrox authors and other industry experts who are present on our mailing lists At p2p.wrox.com youwill find a number of different lists that will help you, not only while you read this book, but also as youdevelop your own applications Particularly appropriate to this book are the Visual Basic and VBAforums, the Database forums, and the DotNet forums
programmer-to-To subscribe to a forum, just follow these steps:
1. Go to http://p2p.wrox.com/
2. Register using the Register link from the left menu bar or log in if you are already a member.
3. Navigate to the appropriate forum.
4. Click the Subscribe to This Forum link for the forum you wish to join
Why this system offers the best support
You can choose to join the mailing lists, or you can receive them as a weekly digest If you don’t have thetime, or facility, to receive the mailing list, you can search our online archives Junk and spam mail isdeleted and your own e-mail address is protected by the unique Lyris system Queries about joining orleaving lists, and any other general queries about lists, should be sent to listsupport@p2p.wrox.com
Trang 26Beginning Visual Basic® 2005 Databases
Trang 28To help you understand how databases are put together, you look also at relational databasedesign This topic describes the relationships between the different tables in your database andhow they can be designed for optimal performance.
At the end of the chapter, you build the sample databases that are used throughout the rest of this
book You’ll be using these databases to perform the Try It Out exercises in each of the chapters.
In this chapter, you:
❑ Learn which components make up a Microsoft Access database
❑ Learn which components make up a Microsoft SQL Server database
❑ Learn which components make up an Oracle database
❑ Learn about relational database design
❑ Build the sample databases used throughout the rest of this book
Trang 29Access Databases
Access databases are common and can be found on most computers, especially if the sample databaseswere installed along with Microsoft Access as a standalone product or as part of Microsoft Office
People use Access databases for a variety of reasons but mainly because they are standalone databases,
meaning that you can create an Access database and then send that database to someone else who, if he
or she has Microsoft Access installed, can open and use your database These databases are easy to use,and Access provides many wizards to help you create a functional database in no time at all
The database engine for Access is the Microsoft Access program MSACCESS.EXE This database enginecan create, open, and edit Access databases and manage the components that make up the database Thedatabase engine is responsible for all the work that controls the database and the data contained in it
You can run this program by clicking Start on the taskbar and then clicking Run In the Run dialog
box, enter MSACCESS and click OK Microsoft Access starts, and depending on which version of
Microsoft Access you have, you may be prompted with a dialog box to open or create a new database.The bottom line is that you can see the database engine at work and the user interface that it provides
Although an Access database may look simple at first glance, it contains a lot of components, typically
referred to as objects All you see as a user is a database file that you can copy and distribute through a
variety of channels The brains behind the actual database itself is the database engine
In this section, you explore some components that make up an Access database to gain a deeper
understanding and appreciation for the complexities that make up an Access database
Database file
An Access database consists of one complex file that stores the various objects that make up the database.You have probably seen the classic sample database Northwind.mdb When you open this database, youcan view the tables, queries, forms, and reports These are some of the objects contained in this databasefile and are controlled by the database engine
Access database files have an mdbfile extension and each database can contain 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 used to enable users to work with and displaydata contained in the database You will be writing Visual Basic 2005 applications to do this, so the onlydatabase 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 Records in a table contain a collection of fields that form a complete record
of information about the data stored in that table For example, suppose a table contains two fields, First
Trang 30Name and Last Name These two fields in a single record describe the name of a single person, as trated in Figure 1-1.
illus-Figure 1-1
Queries
A query in a database is a group of Structured Query Language (SQL) statements that enable you to
retrieve and update data in your tables Queries can be used to select or update all the data in one ormore tables or to select or update specific data in one or more tables
SQL enables you to insert, update, and delete data in a database Microsoft Access provides wizards andvisual tools that enable beginning programmers to write queries without having to know SQL
Using database query objects can make your Visual Basic 2005 code simpler because you have fewer SQLstatements included in your code Database query objects can also make your programs faster becausedatabase engines can compile queries when you create them, whereas the SQL statement in a Visual Basic
2005 program needs to be reinterpreted every time it’s used They also provide ease of maintenancebecause changing a query in your database affects only the database and not your compiled program,which may have been distributed to one or more users
To understand the implications that queries can have on your programs, you need to learn some basicSQL, which you do in Chapter 4
SQL Ser ver Databases
A SQL Server database is more complex than an Access database and the actual database engine for SQLServer is made up of multiple components Also, unlike in an Access database, you cannot simply copy aSQL Server database file and distribute it because SQL Server databases consist of multiple files
Procedures must be followed before you can copy and distribute the database files for a SQL Serverdatabase
SQL Server comes in several editions, such as Microsoft SQL Server 2005 Express, Standard edition, andEnterprise edition However, the components that make up the SQL Server database engine are virtuallythe same for all editions
Many components, other than the database engine and database files, make up SQL Server Theseinclude such components as Replication, Data Transformation Services (DTS), Analysis Services, MetaData Services, and English Query However, those components are beyond the scope of this book, as youwill be focusing your attention on the actual objects that make up a SQL Server database
Trang 31SQL Server is a relational database consisting of many components, each of which contains multipleobjects In the following sections, you examine the main objects that make up a SQL Server database.While you will not examine each and every object of a database, rest assured that what you do learn herewill serve you well, laying the foundation for what you will be doing throughout the rest of this book
A SQL Server database consists of at least two files: a data file and a log file The data file contains all thedata that makes up a SQL Server database, such as tables, indexes, and stored procedures You examinethese objects shortly The log file contains transaction logs, which are records of changes made to thedatabase
When you initially create a SQL Server database, the data file and log file are created by SQL Server; thedata file has an mdfextension and the log file has an ldfextension As your database grows and yourun out of room on the hard drive, your database administrator may create a secondary data file on aseparate hard drive It will typically have an ndffile extension Creating a secondary data file for adatabase typically happens only with large enterprise databases, as most hard drives today can holdmultiple database files on a single drive, given the drives extremely large capacity
Data files
The data file contains multiple objects that make up a database Table 1-1 lists the various objects thatmake up a database and are contained in the data file While you will not be exploring each of theseobjects in detail, it is helpful to know that they exist and what they do
Table 1-1: SQL Server Data File Objects
Object Description
Tables Contains the data in a database, organized in a row-column
format
Keys Primary keys provide a unique value for each row of data in a
table Foreign keys provide a relationship between two tablesusing a column in one table and the primary key in another table
Indexes Provides pointers to rows in a table in a similar fashion that the
index in this book provides pointers to specific topics
Constraints Provides a means by which you can enforce the integrity of a
database, such as not allowing a column to contain a NULLvalue
Stored Procedures A single SQL statement or group of SQL statements
compiled into a single execution plan
Views A SQLSELECTstatement that returns a virtual table
Triggers A special class of stored procedures that are automatically
executed when an Insert, Update, or Deletestatement
is executed against a table
Defaults A default value that is inserted into a column in a table when no
value is supplied
Trang 32Object Description
User-Defined Functions A group of SQL statements that can be encapsulated into a
subroutine that can be called by views and stored procedures
User-Defined Data Types User-defined data types are based on system data types and
enable you to create a data type with attributes that can beapplied to all your tables
User Identifies a user with a database
Roles A group containing certain permissions in the database to
which you add users, effectively assigning the same permissions
to each user
Tables
Tables are core objects that exist in the data file and contain information about your business For example,
you could create an employee table like the one shown in Figure 1-1 that contains information about eachemployee in your organization
Each table that you define is made up of columns and rows Each column represents an attribute aboutthe information stored in your table, such as an employee’s first or last name Collectively, the columnsform a row in your table that represents a single occurrence of the information that the table represents.(Refer to the Employees table in Figure 1-1.)
Keys
Each table in your database usually, but not necessarily, has a column that uniquely identifies each row
of data with a primary key No two rows in a table can contain the same primary key, and SQL Server enforces this rule Primary key columns are usually defined using a globally unique identifier (Guid),
which is a unique value generated based on internal values in your computer No two computers willever generate the same unique identifier
Primary keys may also contain other values such as an employee’s employee number, which could consist
of alpha and numeric characters Also, primary key columns cannot contain NULLvalues ANULLvalue isone missing: it does not exist
When a primary key is created on a table, SQL Server automatically creates a unique index for the primarykey on the table Creating a unique index ensures that no two primary keys can contain the same value.Indexes are covered in detail in the next section Using the index on the primary key column provides fast,efficient access to the data when using the primary key to access data in a table
Foreign keys point to the primary key in another table A foreign key in one row of a table points to an
exact row of data in another table A foreign key value cannot be inserted into a table if the row of datathat it is pointing to in another table does not exist This is just one of the constraints placed on foreignkeys that help ensure referential integrity
Referential integrity enforces the defined relationships between tables when records are inserted ordeleted You cannot insert a foreign key value for a row of data that does not exist in another table.Referential integrity also prevents you from deleting a row of data that is referenced by a foreign key To
Trang 33do so, you must first delete the row of data containing the foreign key or update the column using a
NULLvalue Only then are you able to delete the row containing the primary key
Referential integrity is based on the relationship between foreign and primary keys and ensures that keyvalues are consistent across all tables Referential integrity is automatically enforced by SQL Server andprevents a user from updating a primary or foreign key in a manner that would break the integrity ofthe data
Indexes
An index is an object associated with tables and is built using one or more columns from a table An
index stores information from columns (usually primary and foreign key columns) and the exact location of that data within the table Thus, using an index to access information in the table is very efficient, as SQL Server will use the information contained in the index to find the exact location of therow of data that you want retrieve or update
SQL Server contains two main types of indexes: clustered and non-clustered
Clustered indexes sort the data in the table rows by key, providing an efficient means of accessing data in
the table However, because a clustered index sorts the data in the table, a table can contain only oneclustered index You can think of a clustered index like a phone book The columns that define the index(for example, the last name followed by an initial) are used to sort the table rows A clustered indexstores the data rows of the table in the bottom leaf of the index This means that the index consists of theindex entries pointing to each row of data, and the data rows are stored at the end of the index
Non-clustered indexes store the keys of the table in the index and contain pointers to where the data
actually resides in the table The pointer in a non-clustered index is called a row locator because it actually
locates the row of data in the table
Indexes can be unique or not Unique indexes unique do not allow duplicate keys (keys that contain thesame data value), and indexes that are not defined as unique can contain duplicate keys Index keysshould not be confused with primary keys in a table An index key can be generated for any column in atable that is used to access the data in the table
The last index that I want to cover is the full-text index This type of index is used on columns that contain
the TEXTdata type This is a data type that can store large amounts of data, up to 2 gigabytes worth Thisindex enables you to search through the text in a column containing this data type for specific keywords
Stored procedures
A stored procedure is a single SQL statement or group of SQL statements compiled into an execution plan
and stored under a unique name in the database It is executed as a unit A stored procedure can havemultiple SQL statements to perform such tasks as selecting data from one table and updating data inanother table
Stored procedures increase application performance in a couple of ways First, they enable fewer SQLstatements to be transmitted across the network, as you send only the name of the stored procedure andany parameters it may require
Trang 34Second, stored procedures are similar to procedures and functions in other programming languages, asthey can contain input and output parameters and can return values They use logic to control the flow
of processing, and numerous functions and SQL statements can be used in stored procedures
You can use stored procedures to execute routine functions, such as selecting, inserting, updating, anddeleting data A single stored procedure can be executed by multiple applications, thus providing codereuse You learn more about stored procedures in Chapter 9
Views
A view is like a virtual table containing data from one or more tables A view is stored in the database asthe actual SQL statements that are contained in the view, such as a stored procedure When the view isreferenced, the virtual table is created using the SQL statements that are contained in the view
Views are generally used to enable users to see data from multiple tables in one view, thereby giving theillusion that the data exists as one table or group of data This provides a couple of benefits First, by providing the impression that all of the data is in one table, the complexities of the database are hiddenfrom the user Second, it provides a security mechanism in that you can grant a user access to the viewbut not to the actual tables from which the view is derived, and you can limit the data a user sees
Because a view is like a virtual table, you can execute SQLSELECTstatements against a view, therebyselecting only the data from the view that you need to see You can also limit the results by using a SQL
Whereclause and order the results using a SQLOrder Byclause You learn more about these basic SQL clauses starting in Chapter 4 and more about views in Chapter 9
Log files
Each database that you create has its own transaction log The transaction log contains transactions that
have been applied against your database A transaction is the execution of a group of SQL statements as
one logical unit of work SQL Server automatically manages transactions in the transaction log, generating
a before-and-after picture of the data in a table that is changed This means that you can execute anupdate query to update a row of data and SQL Server logs a record of the data before it was changed andafter it was changed This allows for backward and forward recovery of the data in your database
SQL Server manages transaction logging automatically You can, however, use transactions in yourstored procedures to perform automatic recovery of the data that your stored procedures changed Youcan also use transactions in the ADO.NETclasses that provide data access to your database Transactionsare covered in more depth in Chapter 11
Oracle Databases
Just as SQL Server databases are more complex than Access databases, Oracle databases are more complexthan SQL Server databases Because Oracle was designed to be platform independent, its architecture ismore complex, and a single database in Oracle consists of more files than a SQL Server database
Oracle comes in multiple editions: Enterprise, Standard, and Personal However, the database enginecomponents are virtually the same for all editions Each edition supports features not found in the previous edition For example, the Standard edition supports multiple processors, whereas the Personaledition does not Likewise, the Enterprise edition supports transparent application failover support, butthe Standard edition does not
Trang 35Oracle consists of many components in addition to the database engine, including components that perform data analysis, help you manage XML and image data, manage applications and clusters, andmonitor and manage database performance However, those components are beyond the scope of thisbook, which focuses on the components that make up an Oracle database.
Because Oracle is a relational database, it contains numerous components, and each component containsmany objects In this section, you look at the main objects that make up an Oracle database While thetopics presented here provide only a cursory overview, this information will help you throughout therest of the book
The following sections describe the five file types created when you create an Oracle database
Data files
Data files are perhaps the most important files that make up your database and perhaps among the mostcomplex When an Oracle database is created, a single data file is created However, you can create mul-tiple data files, and most typical production databases contain at least two data files
Data files are complex because they contain the various objects that make up your database In Oracle
ter-minology, these objects are known as segments Because of the complexities of an Oracle data file, Table 1-2
contains only a partial list of the various objects, which you can compare to SQL Server data files
Table 1-2: Oracle Data File Objects
Object Description
Tables Contains the data in a database, organized in a row-column format
Keys Primary keys provide a unique value for each row of data in a table
Foreign keys provide a relationship between two tables using a column in one table and the primary key in another table
Indexes Provides pointers to rows in a table similar to the fashion that the
index in this book provides pointers to specific topics
Constraints Provides a means by which you can enforce the integrity of a
database, such as not allowing a column to contain a NULLvalue
Stored Procedures A group of SQL statements compiled into a single execution plan
Views A SQLSELECTstatement that returns a virtual table
Triggers A special class of stored procedures that are automatically executed
when an Insert, Update, or Deletestatement is executed against a table
Functions A group of SQL statements that can be encapsulated into a subroutine
that can be called by views and stored procedures
User Identifies a user with a database
Roles A group containing certain permissions in the database to which you
add users, effectively assigning the same permissions to each user
Trang 36Indexes in Oracle perform the same function as they do in SQL Server — they provide efficient access to
the data in your tables However, Oracle contains many different kinds of indexes, as outlined in thissection
B*Tree indexes contain four subtypes of indexes: The Index Organized Table index performs the same
function as the clustered index in SQL Server, which is to sort and store the data in the table by the
primary key
The B*Tree cluster index, or index clustered table, stores blocks of data from multiple tables prejoined on the
keys This enables you to select data using a clustered key (a primary and foreign key, for example) andfrom the block that contains the rows related to that clustered key
The reverse key index stores the keys in an index with the key value in reverse order, and is primarily used
on keys that contain sequential numbers For example, suppose your primary keys started with asequential number of 1000 The next primary key would be 1001, and then 1002, and so on The reversekey index stores the primary keys in the index as 0001, 1001, and 2001 This allows the index keys to beinserted into the index spread out over multiple blocks, thereby increasing the efficiency of your index
The descending index enables you to store the primary key for a table in the index in descending
order This is particularly useful when most of the data selected from a table is selected in descendingorder
Bitmap indexes use a single index entry to point to many data rows in a single table This type of index
is particularly useful when indexing columns that contain simple values For example, if a columncontains a value of 0 or 1 or a value of Y or N, this index can use a single index entry to point to all rows
of data that contain the specified value in your query
A function-based index stores the computed results of a function in the index A function is a subroutine
that can be used to encapsulate SQL statements that are repetitively executed and that return a result.For example, the MAXfunction returns the maximum value in a column Using a function-based index ontables that rarely change can increase the performance of your queries
The domain index is a user-defined index that you build yourself You can then tell Oracle about the index
and the query optimizer will decide whether to use the index in your queries This type of index is foradvanced users; in particular, database administrators
The interMedia Text index enables the searching of keywords in large text fields This type of index is
useful for specialized applications such as search engines that need to search huge amounts of text forkeywords entered by the user
Trang 37Redo log files
Oracle’s redo log files are functionally equivalent to log files in SQL Server and enable you to recovertransactions made against the tables in your database However, Oracle databases contain at least tworedo log files and can contain more They are used in a round-robin fashion, whereby the first redo logfile is used until it gets full and then the second redo log file is used When the second one is filled up,the first redo log file is reused
Control files
Oracle uses a single control file per database to tell the database engine where to find the other files, such
as the data and redo log files, associated with a database It also contains other important informationabout your database, such as the database name and the date and time the database was created The control file may also contain other information, such as the location of your archived redo log files
Temp files
Temp files are used to store the intermediate results of large sort operations and large results sets from aquery This provides efficient use of system resources, as smaller sort operations and results sets arestored in the computer’s memory
Password files
Information concerning password files is closely guarded at Oracle and rightly so given the security concerns of corporations everywhere and the fact that Oracle is a very secure database Be aware thatevery database contains password files used to authenticate users performing administrative functionsagainst the database
Relational Database Design
A relational database contains tables, rows, and columns that are related to one another A relational
database that has been properly normalized will have more tables that contain fewer columns, ratherthan a few tables containing lots of columns A normalized relational database actually improves storageefficiency and performance, even though it physically contains more tables than a non-normalizeddatabase does You will be reading about the process of normalization in the next section
Trang 38Each table in your database represents an object about your business, and each column in a table represents an attribute of the object that the table represents A row in the table represents a unique entryfor the object that the table defines
To design a relational database, you must first identify all of the objects that will make up your database
The term object is used to represent a set of information You can also use the term entity in place of
object An entity is an object that refers to a person, place, or thing If you know that you will be building
an application that manages employees in your organization, you first identify which objects representthe information about an employee For example, an employee is an object and the employee’s manager
Employee Name The name of the employee
Phone Number The phone number for the employee
Location The location where the employee works (for example, city, building, or
branch office)
Job Title The job title of the employee
Table 1-4: Manager Attributes
Attribute Description
Manager Name The name of the manager
Phone Number The phone number for the manager
Location The location where the manager works (for example, city, building, or
Manager TableFirstNameLastNamePhoneNumberLocation
Trang 39You’ll also notice that the field names have been defined using Pascal casing Pascal casing is where the
first letter of each word is in uppercase, such as FirstName You can choose to use a field name withspaces in it, such as First Name, or with an underscore in it, such as First_Name Whichever method youchoose to use is fine However, keep in mind that using field names containing spaces forces you to usespecial coding conventions to encapsulate the field name so that the database recognizes it as a singlename and not two separate names Therefore, it’s a good practice to not use spaces in field names
Tables 1-3 and 1-4 illustrate the information that you need, but there is no relationship between the
employee and manager Therefore, you need to create another table that ties the information from thesetwo tables together Let’s call this new table Manager Employees This will enable you to assign employees
to managers
Figure 1-3 shows the new table, which will form the relationships between the Employee and Managertables Because a manager can be responsible for more than one employee, the Manager Employees tablecontains four employee fields
Figure 1-3
This is the start of your relational database design At this point, your database design is relationalbecause the tables relate to one another; however, your design is not yet complete To complete yourdatabase design, you must normalize it
Normalization
Normalization is the process of using formal methods to eliminate duplicate data, and to separate data into
multiple related tables A normalized database offers improved database and application performance over
a database that is not normalized, and over one that has been over-normalized A normalized database alsoleads to more efficient data storage, as you eliminate repeating groups of data Normalization also helps tomake your tables easier to maintain
As normalization increases, so do the number of joins required to access the data; however, relationaldatabase engines are optimized to handle normalized databases that require multiple joins Joins are a logi-cal relationship between two tables that enable you to access data in both tables in the same query Joins areusually defined in the form of foreign key constraints Joins are covered in more detail in Chapter 12
Normalizing a logical database design involves using formal methods to separate the data into multiple,
related tables Each method is typically referred to as a normal form There are three normal forms to a normalized database: first normal form, second normal form, and third normal form An over normalized
database is normalized to fourth and fifth normal forms (which are not covered here) and is rarely considered practical in relational database design The normal forms listed here are discussed in the following sections:
Employee TableFirstNameLastNamePhoneNumberLocationJobTitle
Manager TableFirstNameLastNamePhoneNumberLocation
Manager Employees TableManager
Employee1Employee2Employee3Employee4
Trang 40❑ The first normal form eliminates repeating groups of data in a table You create a separate tablefor each set of related data and identify each table with a primary key, which uniquely identifieseach row of data.
❑ The second normal form creates separate tables for sets of values that apply to multiple records,and relates these tables with foreign keys
❑ The third normal form eliminates columns that do not depend on the primary key
First normal form
You want to apply the rules of normalization to your sample database design, shown previously In thefirst normal form, you need to eliminate repeating groups of data, and create separate tables for each set
of related data You must also identify a primary key for each table
The Manager Employees table contains repeating groups of data so this table is a prime candidate forthe first normal form This table already provides a relationship between a manager and employees, butyou need to eliminate the repeating groups of data (for example Employee1, Employee2) You’ll removethe four individual Employee fields in this table and replace them with a single Employee field Thistable will then provide a one-to-many relationship — one manager to many employees
All tables must have a primary key assigned, as shown in Figure 1-4 A primary key will uniquely identify each record contained in a table Notice that the primary keys shown in Figure 1-4 contain a prefix of the table name and contain a suffix of ID This naming convention will help identify all primaryand foreign keys and which table they belong to Of course, you can use any naming convention thatyou like, but find one that works well for you and use it consistently in your database design
Notice that the Manager Employees table contains a primary key for itself, which will uniquely identifyeach record contained in this table It also contains the primary keys from the Manager and Employeetables These keys, as used in this table, are known as foreign keys, as a table may contain only one primary key
Let’s look at how you can identify the primary and foreign keys in a table using the naming conventionthat has been incorporated here The Manager Employees table contains a field called ManagerEmployeeID.Because this key contains the name of the table and a suffix of ID, you know that this is the primary keyfor this table Likewise, you see two other fields in this table containing a suffix of ID By looking at thenames of these fields you can surmise that the field ManagerID is a foreign key to the Manager table, andthat the field EmployeeID is a foreign key to the Employee table
Figure 1-4
Employee TableEmployeeIDFirstNameLastNamePhoneNumberLocationJobTitle
Manager TableManagerIDFirstNameLastNamePhoneNumberLocation
Manager Employees TableManagerEmployeeIDManagerID
EmployeeID