Upload
jared-white
View
226
Download
0
Tags:
Embed Size (px)
Citation preview
If you have skipped:
• Hands-on exercises of any session– Work on it, or ask classmates, or TA/me
• Any homework– Work on it, or ask classmates, or TA/me
• The Quiz– Work on it on your own
• Discussions of any earlier session– Contribute to your class participation credit!
Agenda
• Relational database design– Relational DB, object-oriented DB, network
DB, hierarchical DB, etc.
• Microsoft Access– DBMS for creating relational DB– Graphical programming interface for skipping
SQL– Oracle, Sybase, MySQL, Dbase, etc.
Databases• Database (DB)
– A DB is a collection of data, organized to support access– DB models some aspects of reality (such as university
enrollment), not everything in the world.– DB has data itself, and the structure of data (for organizing
data).
• Data Base Management System (DBMS)– Software to create and access databases– DBMS is at the level of programming language. Computer
scientists design DBMS. MS-Access is a DBMS.– LSU Computer Science Dept. offers CSC 4402 DBMS.
• Relational Algebra– Special-purpose programming language to create DBMS
Structured Information in DB• Database A collection of tables
• Table A collection of related records– Each record is one row in the table– Each field is one column in the table.
• Record A collection of related fields– A row represents a record.
• Field An “atomic” unit of data– number, string, true/false, …– A column represents a field; models some aspect of the
reality (e.g., attribute of an entity)
• Primary Key The field that uniquely identifies a record– Values of a primary key must be unique
Registrar Example: Enrollment
• Query: which students are in which courses?– Relationship b/t students and courses is assigned
• What do we need to know about the students?– What do you want to know about “students”?– Attributes: first name, last name, email, department– What about professors?
• What do we need to know about the courses?– What do you want to know about “courses”?– Attributes: course ID, description, enrolled students, grades
A “Flat File” Solution Using MS-Excel
Discussion TopicWhy is this a bad approach?
Student ID Last Name First Name Department IDDepartmentCourse ID Course description Grades email1001 Arrows John EE EE LIS7008 Information Technologies 90 jarrows@lsu1001 Arrows John EE Elec Engin ee750 Communication 95 ja_2002@yahoo1002 Peters Kathy HIST HIST LIS 7008 Informatino Technology 95 kpeters2@lsu1002 Peters Kathy HIST history hist405 American History 80 kpeters2@lsu1003 Smith Chris HIST history hist405 American History 90 smith2002@lsu1004 Smith John SLIS Info Sci LIS7008 Information Technology 98 js03@lsu
Goals of “Normalization”• Save space
– Save each fact only once
• More rapid updates– Every fact only needs to be updated once
• More rapid search– Finding something once is good enough
• Avoid inconsistency– Changing data once changes it everywhere
Relational Algebra Terminology• Tables represent “relations”
– “course ID” and “course description” are related.– “Name” and “email address” are related.
• Named fields represent “attributes”– Attributes of Course: course ID, description, …– Attributes of Student: first name, last name, …
• Each row in the table is also called a “tuple”– The order of the rows is not important
• Queries specify desired conditions– The DBMS then finds data that satisfies them
A Normalized Relational Database
Department ID DepartmentEE Electronic EngineeringHIST HistorySLIS Library/Information Sci
Course ID Course DescriptionLIS7008 Information Technologiesee750 Communicationhist405 American History
Student ID Course ID Grades1001 LIS7008 901001 ee750 951002 LIS7008 951002 hist405 801003 hist405 901004 LIS7008 98
Student ID Last Name First Name Department ID email1001 Arrows John EE jarrows@lsu1002 Peters Kathy HIST kpeters2@lsu1003 Smith Chris HIST smith2002@lsu1004 Smith John SLIS js03@lsu
Student Table
Department Table Course Table
Enrollment Table
A foreign key of a table refers to the primary key of an other table. The
Enrollment Table has two foreign keys.
Approaches to Normalization
• For simple problems (like the homework)– Start with “binary relationships”
• Pairs of fields that are related, e.g., Student ID, Last Name
– Group together wherever possible– Add keys where necessary
• For more complicated problems:– Need to do Entity Relationship (E-R) modeling before
designing tables– If interested, read Entity-Relationship Model at
http://en.wikipedia.org/wiki/Entity-relationship_model
Example of Join
Student ID Last Name First Name Department ID email1001 Arrows John EE jarrows@lsu1002 Peters Kathy HIST kpeters2@lsu1003 Smith Chris HIST smith2002@lsu1004 Smith John SLIS js03@lsu
Student Table
Department ID DepartmentEE Electronic EngineeringHIST HistoryCLIS Library/Information Sci
Department Table
Student ID Last Name First Name Department IDDepartment email1001 Arrows John EE Electronic Engineering jarrows@lsu1002 Peters Kathy HIST History kpeters2@lsu1003 Smith Chris HIST History smith2002@lsu1004 Smith John CLIS Library/Information Sci js03@lsu
“Joined” Table
Problems with Join
• Data modeling for “join” is complex
• “Join” is expensive to compute– Both in time and storage space
• But it is “joins” that make databases relational– Projection and restriction are also used in flat files
Some Lingo
• “Primary Key” uniquely identifies a record– e.g. student ID in the Student table
• “Compound” primary key– Synthesize a primary key with a combination of fields– e.g., Student ID + Course ID in the Enrollment table
• “Foreign Key” in this table is a primary key in the other table– Note: it need not be unique in this table
• E.g., Department ID in the Student table is a foreign key; it is a primary key in the Department table.
– Foreign keys are used to “join” other tables
Project
Student ID Last Name First Name Department IDDepartment email1001 Arrows John EE Electronic Engineering jarrows@lsu1002 Peters Kathy HIST History kpeters2@lsu1003 Smith Chris HIST History smith2002@lsu1004 Smith John SLIS Library/Information Sci js03@lsu
New Table
Student ID Department1001 Electronic Engineering1002 History1003 History1004 Library/Information Sci
SELECT Student ID, Department
Restrict
Student ID Last Name First Name Department IDDepartment email1002 Peters Kathy HIST History kpeters2@lsu1003 Smith Chris HIST History smith2002@lsu
Student ID Last Name First Name Department IDDepartment email1001 Arrows John EE Electronic Engineering jarrows@lsu1002 Peters Kathy HIST History kpeters2@lsu1003 Smith Chris HIST History smith2002@lsu1004 Smith John SLIS Library/Information Sci js03@lsu
New Table
SELECT * FROM New Table WHERE Department ID = “HIST”
Entity-Relationship (E-R) Diagrams
• Graphical visualization of the data model– a visual representation of an entity-relationship
model.
• Entities are captured in boxes
• Relationships are captured using arrows
Registrar E-R Diagram
EnrollmentStudentCourseGrade…
StudentStudent IDFirst nameLast nameDepartmentE-mail…
CourseCourse IDCourse Name…
DepartmentDepartment IDDepartment Name…
has
has associated with
offered by
A More Complex E-R Diagram
cadastral: a public record, survey, or map of the value, extent, and ownership of land as a basis of taxation. Source: US Dept. Interior Bureau of Land Management,Federal Geographic Data Committee Cadastral Subcommittee http://www.fairview-industries.com/standardmodule/cad-erd.htm
Databases in the Real World• Some typical database applications:
– Banking (e.g., saving/checking accounts)
– Trading (e.g., stocks)
– Airline reservations
– What if you screwed up your org’s DB?
• Characteristics:– Lots of data
– Lots of concurrent access
– Must have fast access
– “Mission critical”
Database Integrity
• Registrar database must be internally consistent– Enrolled students must have an entry in student table– Courses must have a name
• What happens:– When a student withdraws from the university?
• What tables are affected?
– When a course is taken off the books?
Integrity Constraints
• Conditions that must always be true– Specified when the database is designed– Checked when the database is modified
• R-DBMS ensures integrity constraints are respected– So database contents remain faithful to real world– Helps avoid data entry errors
Referential Integrity
• Foreign key values must exist in other table– If not, those records cannot be joined
• Can be enforced when data is added– Associate a primary key with each foreign key
• Helps avoid erroneous data– Only need to ensure data quality for primary keys
Concurrency
• Thought experiment: You and your project partner are editing the same file…– Scenario 1: you both save it at the same time– Scenario 2: you save first, but before it’s done
saving, your partner saves
Whose changes survive?A) Yours B) Partner’s C) neither D) both E) ???
Concurrency Example• Possible actions on a checking account
– Deposit check (read balance, write new balance)– Cash check (read balance, write new balance)
• Scenario:– Current balance: $500– You try to deposit a $50 check and someone tries
to cash a $100 check at the same time– Possible sequences: (what happens in each case?)
Deposit: read balanceDeposit: write balanceCash: read balanceCash: write balance
Deposit: read balanceCash: read balanceCash: write balanceDeposit: write balance
Deposit: read balanceCash: read balanceDeposit: write balanceCash: write balance
Database Transactions• Transaction: sequence of grouped database actions
– e.g., transfer $500 from checking to savings
• “ACID” properties– Atomicity
• All-or-nothing: either all related transactions made or nothing made
– Consistency• Each transaction must take the DB between consistent states.
– Isolation:• Concurrent transactions must appear to run in isolation
– Durability• Results of transactions must survive even if systems crash
– Transactions are logged
Making Transactions
• Idea: keep a log (history) of all actions carried out while executing transactions– Before a change is made to the database, the corresponding
log entry is forced to a safe location
• Recovering from a crash:– Effects of partially executed transactions are undone– Effects of committed transactions are redone
the log
RideFinder Database Exercise• Suppose you run a small business on campus
– say, Student Ride Booking Company
• Design a database to match passengers with available rides over the Spring Break– Drivers phone in available seats
• They want to know about interested passengers
– Passengers call up looking for rides• They want to know about available rides
– These things happen in no particular order
– Your business is to assign rides to passengers
• This exercise may take 20-30 minutes.
Exercise Goals
• Identify the tables you will need– First decide what data you will save
• What questions will be asked by passengers/drivers?– These will be the queries
– Then decide how to group/split it into tables• Start with binary relations if that helps
• Design the queries– Using join, project and restrict
• Add primary and foreign keys where needed
Exercise Logistics
• Best work in groups of 3 or 4 students– Although you can work by yourself
• Brainstorm data requirements for 5 minutes– Do passengers care about the price of a ride?– Do drivers care how much luggage there is?
• Develop tables and queries for 15 minutes– Don’t get hung up on one thing too long
• Compare your answers with another group– Should take about 5 minutes
How to Read a Database File Using MS-Access
• To view the structure of a table: right-click a table, view "design view".
• To view the data of a table: first view "design view", then click View Datasheet view.
• To view a query: right-click the query, view "design view".
• To run a query: double click the query.
Database “Programming”• Natural language queries
– Goal is ease of use• e.g., Show me the last names of students in SLIS• vocal queries
– Ambiguity sometimes results in errors
• Structured Query Language (SQL)– Consistent, unambiguous interface to any DBMS– Simple command structure:
• e.g., SELECT LastName FROM Students WHERE Dept=SLIS
– Useful standard for inter-process communications
• Visual programming (e.g., Microsoft Access)– Unambiguous, and easier to learn than SQL
SQL: The SELECT Command
• Project chooses columns– Based on their label
• Restrict chooses rows– Based on their contents
• e.g. department ID = “HIST”
• These can be specified together– SELECT Student ID, Dept FROM New Table WHERE
Department ID = “HIST”
SQL: Restrict Operators
• Each SELECT contains a single WHERE
• Numeric comparison <, >, =, <>, …
• e.g., grade<80; price<20
• Boolean operations – e.g., Name = “John” AND DeptID <> “HIST”– <> means not equal to
Using Microsoft AccessProcedure
• Create a DB– Click Blank Database– Define file name (e.g., mydb.accdb)– Click Create
• Create Tables– Click Create Table– In the Ribbon, get Design View of the table– Define table name, save– Name your fields, specify field properties– Define Primary Key (a field of a table)
MS-AccessCreate Records and Relationships
• Create Records– Get a table’s Datasheet View– Input data for each record– Click Save icon when done
• Create/add Relationships– Click Database Tool tab – Click Relationships– To create/add a relationship between two tables:
• put cursor on one field of a table, click and drag it onto a field of another table
MS-Access Create Queries
• Click Create Query Design
• Select the tables involved
• Define fields and criteria
• Define query name, save
• Double click the query to run
MS-Access 2010 Tutorials
• My tutorial:– http://www.csc.lsu.edu/~wuyj/Teaching/7008/
sp14/SampleDB/Access2010/Access2010.html
• Other people’s tutorials: – See syllabus page (under Useful Resources)
MS-Access 2007 Tutorials
• My tutorial:– http://www.csc.lsu.edu/~wuyj/Teaching/7008/
sp14/SampleDB/Access2007/Access2007.html
• Other people’s tutorials: – See the syllabus page (under Useful Resources)– http://holowczak.com/microsoft-access-2007-and-2010-tutorial/
– http://inpics.net/tutorials/access2007/basics.html
– http://www.officetutorials.com/Access%202007%20tut.DOC
MS-Access 2000-2003 Tutorials
• My tutorial: http://www.csc.lsu.edu/~wuyj/Teaching/7008/sp14/SampleDB/Access2000/Access2000.html
• Other tutorials: – http://www.cwnresearch.com/resources/databases/
access/tutorials/access2000/Access2000Tutorial.html
– https://www.courses.psu.edu/infsy/infsy540_gjy1/access_tutorial_2000.html
Using Microsoft Access 2000-2003
• Create a database called rides.mdb– FileNewBlank Database
• Specify the fields (columns)– “Create a Table in Design View”
• Fill in the records (rows)– Double-click on the icon for the table
MS-Access 2000-2003 Creating Fields
• Enter field name– Must be unique, but only within the same table
• Select field type from a menu– Use date/time for times– Use text for phone numbers
• Designate primary key (right mouse button)
• Save the table– That’s when you get to assign a table name
MS-Access 2000-2003 Entering Data
• Open the table– Double-click on the icon
• Enter new data in the bottom row– A new (blank) bottom row will appear
• Close the table– No need to “save” – data is stored automatically
MS-Access 2000-2003 Building Queries
• Copy ride.mdb to your computer
• “Create Query in Design View”– In “Queries”
• Choose two tables
• Pick each field you need using the menus– Unclick “show” to not project– Enter a criterion to “restrict”
• Save, exit, and reselect to run the query
Fun Facts about Queries
• “Joins” are automatic if field names are same– Otherwise, drag a line between the fields
• Sort order is easy to specify– Use the menu
• Queries form the basis for reports– Reports give good control over layout
– Use the report wizard - the formats are complex
Other Things to Know
• Data input forms manage input better than raw tables– Invalid data can be identified when input– Graphics can be incorporated
Key Ideas
• Relational Databases are a good choice when you have:– Lots of data– And a problem that contains inherent relationships
• Design before you implement– This is just another type of programming– The mythical person-month applies!
• Join is the most important concept– Project and restrict just remove undesired stuff
Discussion Point: Mythical Person-Month
• Why is software development different from manufacturing car?
• If it would take 1 person 3 months, why does it take 4 people 6 months?
• Reminder: read the Mythical Person-Month paper posted on the syllabus page
Trading People and Months is Hard
• Sequential constraints – in the procedure of software development
• Communication– between team members
• Training– if new members join the team
Estimating Completion Time
• Rules of thumb– 1/3 specification
– 1/6 coding
– 1/2 test planning, testing, and fixing!
– This applies to your course project!
• Add time for coding to learn as you go, but don’t take time away from the other parts!– Reread the section on “gutless estimating” if you are
tempted
HW5: “type mismatch in query"
• Problem1: Every time I run a query it says "Type mismatch in query."
• Problem 2: My database cannot enforce referential integrity.
• Solution: In order to remain data integrity, databases declares the types of data. For instance, if the StudentID in Table1 is a "string" type, and the StudentID in Table2 is a "number" type, when you want to relate the two fields, the DBMS reports a "type mismatch" error. So to correct such a mistake, you need to go back to the structures of the both tables, and check the types of the two fields to make sure their types match.