Presentation is loading. Please wait.

Presentation is loading. Please wait.

Databases Intro (from Deitel)

Similar presentations


Presentation on theme: "Databases Intro (from Deitel)"— Presentation transcript:

1 Databases Intro (from Deitel)

2 Databases A database is an organized collection of data
A database management system (DBMS) provides mechanisms for storing, organizing, retrieving and modifying data for many users SQL is the international standard language used with relational databases to perform queries and to manipulate data Popular relational database management systems (RDBMSs) Microsoft SQL Server Oracle Sybase IBM DB2 Informix PostgreSQL MySQL 2

3 A relational database stores data in tables
A relational database is a logical representation of data that allows the data to be accessed without consideration of its physical structure A relational database stores data in tables Tables are composed of rows, and rows are composed of columns in which values are stored Primary key —a column (or group of columns) with a unique value that cannot be duplicated in other rows 3

4 Relational Databases

5 Books Database The database consists of three tables: Authors
AuthorISBN Titles The Authors table consists of three columns that maintain each author’s unique ID number, first name and last name The AuthorISBN table consists of two columns that maintain each ISBN and the corresponding author’s ID number The Titles table consists of four columns that stand for the ISBN, the title, the edition number and the copyright year Foreign key —a column in a table that matches the primary key column in another table. Helps maintain the Rule of Referential Integrity—every foreign-key value must appear as another table’s primary-key value There is a one-to-many relationship between a primary key and a corresponding foreign key 5

6 A Books Database

7

8 Books Database (cont.) Entity-relationship (ER) diagram for the books database Shows the database tables and the relationships among them The names in italic are primary keys A table’s primary key uniquely identifies each row in the table Every row must have a primary-key value, and that value must be unique in the table This is known as the Rule of Entity Integrity 8

9

10

11 SQL (basics)

12 SQL SELECT A SQL query “selects” rows and columns from one or more tables in a database. The basic form of a SELECT query is SELECT * FROM tableName in which the asterisk (*) wildcard character indicates that all columns from the tableName table should be retrieved. To retrieve all the data in the Authors table, use SELECT * FROM Authors To retrieve only specific columns, replace the asterisk (*) with a comma-separated list of the column names, e.g., SELECT AuthorID, LastName FROM Authors 12

13 WHERE Close In most cases, only rows that satisfy selection criteria are selected SQL uses the optional WHERE clause in a query to specify the selection criteria for the query The basic form of a query with selection criteria is SELECT columnName1, columnName2, … FROM tableName WHERE criteria To select the Title, EditionNumber and Copyright columns from table Titles for which the Copyright date is greater than 2005, use the query SELECT Title, EditionNumber, Copyright FROM Titles WHERE Copyright > '2005' Strings in SQL are delimited by single (') rather than double (") quotes The WHERE clause criteria can contain the operators <, >, <=, >=, =, <> and LIKE 13

14 Operator LIKE Operator LIKE is used for pattern matching with wildcard characters percent (%) and underscore (_) A pattern that contains a percent character (%) searches for strings that have zero or more characters at the percent character’s position in the pattern For example, the next query locates the rows of all the authors whose last name starts with the letter D: SELECT AuthorID, FirstName, LastName FROM Authors WHERE LastName LIKE 'D%' 14

15 Other Patterns Wildcard character Description Example %
Any string of zero or more characters. WHERE title LIKE '%computer%' finds all book titles with the word 'computer' anywhere in the book title. _ (underscore) Any single character. WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on). [ ] Any single character within the specified range ([a-f]) or set ([abcdef]). WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation. [^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]). WHERE au_lname LIKE 'de[^l]%' all author last names starting with de and where the following letter is not l.

16 ORDER BY Clause The rows in the result of a query can be sorted into ascending or descending order by using the optional ORDER BY clause. The basic form of a query with an ORDER BY clause is SELECT columnName1, columnName2, … FROM tableName ORDER BY column ASC SELECT columnName1, columnName2, … FROM tableName ORDER BY column DESC ASC specifies ascending order (lowest to highest) DESC specifies descending order (highest to lowest) column specifies the column on which the sort is based. To obtain the list of authors in ascending order by last name (), use the query SELECT AuthorID, FirstName, LastName FROM Authors ORDER BY LastName ASC To obtain the same list of authors in descending order by last name (), use the query SELECT AuthorID, FirstName, LastName FROM Authors ORDER BY LastName DESC Multiple columns can be used for sorting with an ORDER BY clause of the form ORDER BY column1 sortingOrder, column2 sortingOrder, … sortingOrder is either ASC or DESC. Sort all the rows in ascending order by last name, then by first name. SELECT AuthorID, FirstName, LastName FROM Authors ORDER BY LastName, FirstName 16

17 ORDER BY Clause cont The WHERE and ORDER BY clauses can be combined in one query, as in SELECT ISBN, Title, EditionNumber, Copyright FROM Titles WHERE Title LIKE '%How to Program' ORDER BY Title ASC which returns the ISBN, Title, EditionNumber and Copyright of each book in the Titles table that has a Title ending with "How to Program" and sorts them in ascending order by Title 17

18 ActiveX Data Objects (ADO)
SqlConnection con = new SqlConnection(...); con.Open(); SqlCommand cmd = new SqlCommand( @"SELECT * FROM Customers WHERE c.Region con ); "US"); DataReader dr = cmd.ExecuteReader(); while (dr.Read()) { string name = dr.GetString(dr.GetOrdinal("Name")); string phone = dr.GetString(dr.GetOrdinal("Phone")); DateTime date = dr.GetDateTime(3); } dr.Close(); con.Close(); Hard to write database-neutral SQL because of subtle variances in the parameters, escaping, types etc.

19 AirlineReservation Db connection
private SqlConnection connectToDatabase() { SqlConnection con = new 18\AirlineReservation3\AirlineReservation\AirlineReservationDb .mdf;Integrated Security=True"); return con; }

20 Save seats SqlConnection con = null; try { con = connectToDatabase(); if (con != null) { con.Open(); } SqlCommand deleteCommand = new SqlCommand("DELETE FROM SeatsTable", con); //always //delete first int rowsDeleted = deleteCommand.ExecuteNonQuery(); for (int i = 0; i < seats.Length; i++) { SqlCommand insertCommand = new SqlCommand("INSERT INTO SeatsTable (seatNumber, con); SqlDbType.Int).Value = i; SqlDbType.Bit).Value = seats[i]; int rowsInserted = insertCommand.ExecuteNonQuery(); Console.WriteLine("Saved seat {0} reserved {1} ", i, seats[i]); return true; catch (SqlException ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); return false; finally { con.Close();


Download ppt "Databases Intro (from Deitel)"

Similar presentations


Ads by Google