Upload
erica-page
View
230
Download
3
Embed Size (px)
Citation preview
ASP.NET Programming with C# and SQL Server
First Edition
Chapter 7Working with Databases and
SQL Server Express
Objectives
In this chapter, you will:
• Study the basics of databases and SQL Server
• Work with SQL Server databases
• Define database tables
• Work with database records
ASP.NET Programming with C# and SQL Server, First Edition 2
Introduction to Databases
• Database: an ordered collection of information from which a computer program can quickly access information
• Information in computer databases is stored in tables similar to spreadsheets
• Record: a single complete set of related information
• Field: an individual category of information stored in a record
ASP.NET Programming with C# and SQL Server, First Edition 3
Introduction to Databases (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 4
Figure 7-1 Employee directory database
Introduction to Databases (cont’d.)
• Flat-file database: stores information in a single table– Useful for simple collections of information
• Relational database: stores information across multiple related tables– Better for large and complex databases
ASP.NET Programming with C# and SQL Server, First Edition 5
Understanding Relational Databases
• Relational databases consist of one or more related tables
• Primary table: the main table in a relationship that is referenced by another table
• Related (or child) table: references a primary table in a relational database
• Tables in a relationship are connected using primary and foreign keys– Primary and foreign keys link records across multiple
tables
ASP.NET Programming with C# and SQL Server, First Edition 6
Understanding Relational Databases (cont’d.)
• Primary key: a field that uniquely identifies a record in a table
• Foreign key: a field in a related table that refers to the primary key in a primary table
• Index: a field that identifies records in a database to make retrievals and sorting faster– Primary key is a type of index– Index may consist of one field or a combination of
multiple fields
ASP.NET Programming with C# and SQL Server, First Edition 7
Understanding Relational Databases (cont’d.)
• Three basic types of relationships in a relational database:– One-to-one– One-to-many– Many-to-many
• One-to-one relationship: there is exactly one record in a related table for each record in the primary table– Used to break information into multiple, logical sets– Information in a one-to-one relationship could be
placed within a single tableASP.NET Programming with C# and SQL Server, First Edition 8
Understanding Relational Databases (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 9
Figure 7-2 One-to-one relationship
Understanding Relational Databases (cont’d.)
• One-to-many relationship: one record in a primary table has many related records in a related table– Used to eliminate redundant information– Only the primary and foreign keys are duplicated
• Normalization: the process of breaking tables into multiple related tables to reduce redundant and duplicate information – Reduces the overall size of the database
ASP.NET Programming with C# and SQL Server, First Edition 10
Understanding Relational Databases (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 11
Figure 7-3 Table with redundant information
ASP.NET Programming with C# and SQL Server, First Edition 12
Figure 7-4 One-to-many relationship
Understanding Relational Databases (cont’d.)
• Many-to-many relationship: many records in one table are related to many records in another table
• Junction table: creates a one-to-many relationship for each of the two tables in a many-to-many relationship– Contains foreign keys from the two tables in the
many-to-many relationship
ASP.NET Programming with C# and SQL Server, First Edition 13
ASP.NET Programming with C# and SQL Server, First Edition 14
Figure 7-5 Many-to-many relationship
Working with Database Management Systems
• Database management system (or DBMS): an application or collection of applications used to access and manage a database
• Schema: the structure of a database– Includes its tables, fields, and relationships
• Flat-file database management system: stores data in a flat-file format
• Relational database management system (or RDBMS): stores data in a relational format
ASP.NET Programming with C# and SQL Server, First Edition 15
Working with Database Management Systems (cont’d.)
• Popular commercial relational database managements systems include:– Microsoft SQL Server– Oracle– Sybase– Informix– Microsoft Access
• Popular open source relational database management systems include:– MySQL– PostgresSQL
ASP.NET Programming with C# and SQL Server, First Edition 16
Working with Database Management Systems (cont’d.)
• Functions of a DBMS:– Creating new database files– Allowing users to enter and manipulate data– Structuring and preservation of the database file(s)– Ensuring that data is stored correctly in tables– Ensuring that relationships are enforced– Providing authentication and authorization features
• Query: a structured set of instructions and criteria for retrieving, adding, modifying, and deleting database information
ASP.NET Programming with C# and SQL Server, First Edition 17
Working with Database Management Systems (cont’d.)
• Data manipulation language (or DML): a language for creating queries
• Structured Query Language (or SQL): supported by most DBMSs for creating queries
• Most DBMSs provide an interface to design queries– Must still learn SQL for programmatically accessing
a database
• Each DBMS creates its own proprietary file types– Most have the ability to import data from other file
formats but cannot directly read each other’s files
ASP.NET Programming with C# and SQL Server, First Edition 18
Querying Databases with Structured Query Language
• SQL has become an official standard for querying databases
• SQL statements are composed of keywords that perform actions on a database
• SELECT statement returns data from the database
ASP.NET Programming with C# and SQL Server, First Edition 19
Querying Databases with Structured Query Language (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 20
Table 7-1 Common SQL keywords
Getting Started with SQL Server
• Microsoft SQL Server Management Studio Express: a graphic tool for manipulating SQL Server databases
• New Query window: used to execute SQL commands
• SQL Server Query Designer: a graphic tool for creating queries in a graphical environment– Can drag fields from table objects or can center SQL
commands directly
ASP.NET Programming with C# and SQL Server, First Edition 21
Getting Started with SQL Server (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 22
Figure 7-6 Microsoft SQL Server Management Studio Express
Getting Started with SQL Server (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 23
Figure 7-7 Query window in SQL Server Management Studio Express
Getting Started with SQL Server (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 24
Figure 7-8 Query Designer in SQL Server Management Studio Express
Installing SQL Server 2008 Management Studio Express
• To install SQL Server Management Studio Express:– Download the installation package from Microsoft’s
Web site– Start the installation package that you downloaded– Select Installation link– Select New SQL Server stand-alone installation or
add features to an existing installation link– Follow the rest of the on-screen instructions to
complete the installation
ASP.NET Programming with C# and SQL Server, First Edition 25
Working with the SQL Server Management Studio Express
• Query window allows you to enter SQL commands– Does not have a graphical interface
• SQL commands must be terminated with a semicolon– If no semicolon, the query window assumes you
want to enter more SQL statements
• From the Query menu, select Execute to execute the SQL commands in the query window
• Results window displays the results of executing the SQL commands
ASP.NET Programming with C# and SQL Server, First Edition 26
ASP.NET Programming with C# and SQL Server, First Edition 27
Figure 7-9 Results window showing results of a SQL query
ASP.NET Programming with C# and SQL Server, First Edition 28
Figure 7-10 Output from a multiline SQL command
Working with the SQL Server Management Studio Express (cont’d.)
Understanding SQL Server Identifiers
• You must define identifiers (names) for databases, tables, fields, and indexes
• Two types of identifiers:– Regular identifiers: must begin with a letter,
underscore (_), number sign (#) or at sign (@)– Delimited identifiers: enclosed by double
quotations (“”) or brackets ([]), and may contain spaces or other characters not allowed in regular identifiers
ASP.NET Programming with C# and SQL Server, First Edition 29
Understanding SQL Server Identifiers (cont’d.)
• To use SQL Server Management Studio Express, you must connect to a server
• Instance: refers to a single SQL Server database– An installation of SQL Server can have many
instances– Default instance is named SQLEXPRESS
• Authentication types:– Windows Authentication– SQL Server Authentication
ASP.NET Programming with C# and SQL Server, First Edition 30
Understanding SQL Server Identifiers (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 31
Figure 7-11 Connect to Server dialog box
Working with SQL Server Databases
• The basics of working with databases in SQL Server include:– Creating databases– Deleting databases– Specifying field data types– Creating tables– Deleting tables
ASP.NET Programming with C# and SQL Server, First Edition 32
Creating Databases
• Use the CREATE DATABASE statement to create a new database
• Syntax:
CREATE DATABASE databaseName;– databaseName must be unique
• New databases are created with a file extension of .mds
• Can specify the location for the database using the FILENAME keyword
• Must define tables and fields after creating the database
ASP.NET Programming with C# and SQL Server, First Edition 33
Deleting Databases
• Use the DROP DATABASE statement to delete a database– This removes all tables from the database and
deletes the database itself
• Syntax:
DROP DATABASE databaseName;
ASP.NET Programming with C# and SQL Server, First Edition 34
Specifying Field Data Types
• Fields in a database store data according to type– Data type determines the amount of memory and
storage space required for the field
• SQL Server includes numeric, string, monetary, and date/time data types
• Choose the smallest data type possible for each field
ASP.NET Programming with C# and SQL Server, First Edition 35
ASP.NET Programming with C# and SQL Server, First Edition 36
Table 7-2 Common SQL Server data types
Creating Tables
• Use the CREATE TABLE statement to specify the table, the column names, and the data type for each column
• Syntax:CREATE TABLE tableName (columnName Type, …);
• Column names must be unique within a table
• Table names must be unique with the database
• Must select the database with the USE database statement first to use it in a query window
ASP.NET Programming with C# and SQL Server, First Edition 37
Deleting Tables
• Use the DROP TABLE statement to remove all data from a table and delete the table definition
• Syntax:
DROP TABLE tableName;
ASP.NET Programming with C# and SQL Server, First Edition 38
Working with Records
• Working with records includes:– Adding records to a table– Modifying existing records in a table– Deleting existing records in a table
ASP.NET Programming with C# and SQL Server, First Edition 39
Adding Records
• Use the INSERT statement to add a single new record to a table
• Syntax:
INSERT INTO tableName VALUES (value1,value2,…);
• Text values are enclosed within single quotations
• Values in the VALUES list must be in the same order in which the fields are defined in the table– Specify NULL in any fields for which you do not have a
value
ASP.NET Programming with C# and SQL Server, First Edition 40
Adding Records (cont’d.)
• Use the BULK INSERT statement with a local text file to add multiple records to an existing database
• Syntax:
BULK INSERT tableName FROM ‘filePath’;
• Each record in the text file should be on a separate line with tabs between each field– Leave empty fields blank
• Values on each line must be in the same order as the fields are defined in the table
ASP.NET Programming with C# and SQL Server, First Edition 41
ASP.NET Programming with C# and SQL Server, First Edition 42
Figure 7-12 Results window after adding records to the outlook table in the forecast database
Adding Records (cont’d.)
Retrieving Records
• Use a SELECT statement to retrieve records from a table
• Syntax:
SELECT criteria FROM tableName;
• Use * to select all fields, or list individual field names separated by commas
ASP.NET Programming with C# and SQL Server, First Edition 43
ASP.NET Programming with C# and SQL Server, First Edition 44
Figure 7-13 Individual fields returned with a SELECT statement
Retrieving Records (cont’d.)
Sorting Query Results
• Use the ORDER BY keyword with the SELECT statement to sort results alphanumerically
• Syntax:
SELECT criteria FROM tableName
ORDER BY fieldName;
• Add the DESC keyword to sort in reverse (in descending order)
ASP.NET Programming with C# and SQL Server, First Edition 45
ASP.NET Programming with C# and SQL Server, First Edition 46
Figure 7-14 Results returned from inventory table of the skateboards database sorted by price
Sorting Query Results (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 47
Figure 7-15 Results returned from inventory table of the skateboards database reverse sorted by price
Sorting Query Results (cont’d.)
Filtering Query Results
• Use the criteria portion of the SELECT statement to determine which fields to retrieve from a table
• Use the WHERE keyword to specify which records to return
• Syntax:
SELECT criteria FROM tableName
WHERE condition;
• Can use AND and OR keywords to specify more detailed conditions in the WHERE clause
ASP.NET Programming with C# and SQL Server, First Edition 48
ASP.NET Programming with C# and SQL Server, First Edition 49
Figure 7-16 Results returned from the inventory table of the skateboards database where price is less than 100
Filtering Query Results (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 50
Figure 7-17 Results returned from the inventory table of the skateboards database where price is greater than 100 and length is less than 30
Filtering Query Results (cont’d.)
ASP.NET Programming with C# and SQL Server, First Edition 51
Figure 7-18 Results returned from the inventory table of the skateboards database where price is greater than 100 or length is less than 30
Filtering Query Results (cont’d.)
Updating Records
• Use the UPDATE statement to update existing records in a table
• Syntax:
UPDATE tableName
SET columnName=value
WHERE condition;
• Must use a WHERE condition to specify which record to update
ASP.NET Programming with C# and SQL Server, First Edition 52
Deleting Records
• Use the DELETE statement to delete existing records in a table
• Syntax:
DELETE FROM tableName
WHERE condition;
• Must use the WHERE clause to specify which record(s) to delete
ASP.NET Programming with C# and SQL Server, First Edition 53
Summary
• A database is an ordered collection of information from which a computer program can quickly access information
• A record is a single complete set of related information
• Fields are individual categories of information stored in a record
• Flat-file database stores information in a single table
• Relational database stores information across multiple tables
ASP.NET Programming with C# and SQL Server, First Edition 54
Summary (cont’d.)
• A query is a structured set of instructions and criteria for retrieving, adding, modifying, and deleting database information
• Structured Query Language (SQL) has become a standard data manipulation language for many database management systems
• Microsoft SQL Server Management Studio Express is a graphic tool for manipulating a SQL Server database
• Regular identifiers begin with a letter, underscore, number sign, or at sign
ASP.NET Programming with C# and SQL Server, First Edition 55
Summary (cont’d.)
• Delimited identifiers allow spaces and other characters, enclosed within double quotations or brackets
• Use the USE statement to select a database to work with
• Use the CREATE DATABASE statement to create a new database
• Use the DROP DATABASE statement to delete a database
• Choose the smallest data type possible for each field in a table
ASP.NET Programming with C# and SQL Server, First Edition 56
Summary (cont’d.)
• Use the CREATE TABLE statement to create a new table and specify the column names and data types
• Use the DROP TABLE statement to delete a table
• Use the INSERT statement to add a single record to a table
• Use the BULK INSERT statement to add multiple records to a table from a local text file
• Use the SELECT statement to retrieve records from a table
ASP.NET Programming with C# and SQL Server, First Edition 57
Summary (cont’d.)
• Use the ORDER BY keyword in a SELECT statement to sort the results returned by a query
• Use the WHERE keyword to specify which records to return from a database
• Use the UPDATE statement to update records in a table
• Use the DELETE statement to delete records in a table
ASP.NET Programming with C# and SQL Server, First Edition 58