CS 586/486 Fall 2016, Lecture Notes 5

Similar documents
Database Programming. Week *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University

JDBC (Java / SQL Programming) CS 377: Database Systems

More SQL: Assertions, Views, and Programming Techniques

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd.

SQL and Java. Database Systems Lecture 19 Natasha Alechina

Java and Databases. COMP514 Distributed Information Systems. Java Database Connectivity. Standards and utilities. Java and Databases

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

The Relational Model. Why Study the Relational Model? Relational Database: Definitions. Chapter 3

Mimer SQL. Programmer s Manual. Version 8.2 Copyright 2000 Mimer Information Technology AB

Programming Database lectures for mathema

SQL and programming languages

Database Design Overview. Conceptual Design ER Model. Entities and Entity Sets. Entity Set Representation. Keys

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

What is ODBC? Database Connectivity ODBC, JDBC and SQLJ. ODBC Architecture. More on ODBC. JDBC vs ODBC. What is JDBC?

CS346: Database Programming.

Seminar Datenbanksysteme

Database Programming with PL/SQL: Learning Objectives

Guide to Upsizing from Access to SQL Server

SQL and Programming Languages. SQL in Programming Languages. Applications. Approaches

Lecture 6. SQL, Logical DB Design

COSC344 Database Theory and Applications. Java and SQL. Lecture 12

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

Database Query 1: SQL Basics

Data Modeling. Database Systems: The Complete Book Ch ,

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1

Real SQL Programming 1

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Review: Participation Constraints

EXEC SQL CONNECT :userid IDENTIFIED BY :passwd;

Understanding Sql Injection

SQL is capable in manipulating relational data SQL is not good for many other tasks

Using SQL Server Management Studio

The JAVA Way: JDBC and SQLJ

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

SQL SELECT Query: Intermediate

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

Database programming made easier Master thesis of Roland Balk

COSC 6397 Big Data Analytics. 2 nd homework assignment Pig and Hive. Edgar Gabriel Spring 2015

A Brief Introduction to MySQL

Talking to Databases: SQL for Designers

SQL. Short introduction

Overview. Database Application Development. SQL in Application Code (Contd.) SQL in Application Code. Embedded SQL. Embedded SQL: Variables

ASP.NET Programming with C# and SQL Server

not necessarily strictly sequential feedback loops exist, i.e. may need to revisit earlier stages during a later stage

Supplement IV.D: Tutorial for MS Access. For Introduction to Java Programming By Y. Daniel Liang

Real SQL Programming. Embedded SQL Call-Level Interface Java Database Connectivity

CHAPTER 5 INTELLIGENT TECHNIQUES TO PREVENT SQL INJECTION ATTACKS

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

Creating Database Tables in Microsoft SQL Server

Managing Objects with Data Dictionary Views. Copyright 2006, Oracle. All rights reserved.

How I hacked PacketStorm ( )

Oracle For Beginners Page : 1

Database System Concepts

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

The Entity-Relationship Model

T-SQL STANDARD ELEMENTS

Relational Databases. Christopher Simpkins

UQC103S1 UFCE Systems Development. uqc103s/ufce PHP-mySQL 1

Database Access via Programming Languages

TECH TUTORIAL: EMBEDDING ANALYTICS INTO A DATABASE USING SOURCEPRO AND JMSL

CS/CE 2336 Computer Science II

FileMaker 14. ODBC and JDBC Guide

DATABASE MANAGEMENT SYSTEMS. Question Bank:

Real SQL Programming. Persistent Stored Modules (PSM) PL/SQL Embedded SQL

Crystal Reports Form Letters Replace database exports and Word mail merges with Crystal's powerful form letter capabilities.

IT2305 Database Systems I (Compulsory)

Fundamentals of Database System

Using IRDB in a Dot Net Project

Financial Data Access with SQL, Excel & VBA

1 SQL Data Types and Schemas

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Using Temporary Tables to Improve Performance for SQL Data Services

The C Programming Language course syllabus associate level

14 Triggers / Embedded SQL

IT2304: Database Systems 1 (DBS 1)

Chapter 13. Introduction to SQL Programming Techniques. Database Programming: Techniques and Issues. SQL Programming. Database applications

Introduction to Database. Systems HANS- PETTER HALVORSEN,

Accessing Your Database with JMP 10 JMP Discovery Conference 2012 Brian Corcoran SAS Institute

CSC 443 Data Base Management Systems. Basic SQL

Chapter 22 Database: SQL, MySQL,

Introduction to the Oracle DBMS

Database Application Development. Overview. SQL in Application Code. Chapter 6

Database Design and Programming

Serious Threat. Targets for Attack. Characterization of Attack. SQL Injection 4/9/2010 COMP On August 17, 2009, the United States Justice

Darshan Institute of Engineering & Technology PL_SQL

INTERNET PROGRAMMING AND DEVELOPMENT AEC LEA.BN Course Descriptions & Outcome Competency

An Oracle White Paper June Migrating Applications and Databases with Oracle Database 12c

Java (12 Weeks) Introduction to Java Programming Language

LSINF1124 Projet de programmation

Web Application Disassembly with ODBC Error Messages By David Litchfield Director of Security

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

Instant SQL Programming

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

12 File and Database Concepts 13 File and Database Concepts A many-to-many relationship means that one record in a particular record type can be relat

Transcription:

Converting ER to Relational Schema Lecture 5 - Translating an ER Diagram to a Relational Schema - Embedded SQL 0..* Assignment 0..* 0..* Manager 1..1 Some slides 1 2 1. Translate each entity set into a table, with keys. Entity set: can be represented as a table in the relational model has a key which becomes a key for the table CREATE TABLE ( CHAR(11) NOT NULL, CHAR(20), INTEGER, PRIMARY KEY ()) Multi-valued Attribute One or more values of same attribute for an entity Name Ctype Character Stamina Special moves Attack Quick moves 3 4 1

Most relational DBMSs do not allow multivalued attributes. 2. Create a table for each multi-valued attribute. Key is entity key plus the attribute Character(Name, Stamina, Attack) Ctypes(Name, Ctype) QuickMoves(Name, QuickMove) SpecialMoves(Name, SpecialMove) 0..* Assignment 0..* 0..* Manager 1..1 3. Translate each many-to-many relationship set into a table What are the attributes and what is the key for Assignment? (,, ) (,, ) Some slides 5 Some slides 6 0..* Assignment 0..* 0..* Manager 1..1 0..* Assignment 0..* 0..* Manager 1..1 Answer: Assignment(P-Number, ) P-Number is a foreign key for is a foreign key for (P-Number, P-) (,, ) What should we do with each one-to-many relationship set? Manager (?) (,, ) (,, ) 7 Some slides 8 2

0..* Assignment 0..* 0..* Manager 1..1 (,,, Mgr) (,, ) 4. Create a foreign key for a 1-to-many relationship set. Mgr is a foreign key (referencing the relation) value of Manager must match an 0..* Assignment 0..* 0..* Manager 1..1 (,,, Mgr) (,, ) vs. 4. Or...Create a table for a 1-many relationship set. (,, ) (,, ) Manager(, ) What are the tradeoffs between these two? Note: is the key for Manager Some slides 9 Some slides 10 Assignment role start-date end-date Assignment role start-date end-date What do we do when a many-to-many relationship set has an attribute? What do we do when a many-to-many relationship set has an attribute? Assignment(, ) (,, ) (,, ) Assignment(,, role, start-date, end-date) (,, ) (,, ) Some slides 11 Some slides 12 3

Manager start-date end-date Manager start-date end-date What do we do when a 1-to-many relationship set has an attribute? What do we do when a 1-to-many relationship set has an attribute? (,,, Mgr) (,, ) (,,, Mgr, start-date, end-date) (,, ) Some slides 13 Some slides 14 Weak Entity Sets Translating Weak Entity Sets name office Insures Policy dep-name cost strong entity set identifying relationship set weak entity set Weak entity sets and identifying relationship sets are translated into a single table. Must include key of strong entity set, as a foreign key. When the owner entity is deleted, all owned weak entities must also be deleted. CREATE TABLE Insurance_Policy ( dep-name CHAR(20), cost REAL, ssn CHAR(11) NOT NULL, PRIMARY KEY (dep-name, ssn), FOREIGN KEY (ssn) REFERENCES, ON DELETE CASCADE) 15 16 4

ER to Tables, Method 1 Create table and choose key for each entity set; include singlevalued attributes. Create table for each weak entity set; include single-valued attributes. Include key of owner as a foreign key in the weak entity. Set key as foreign key of owner plus local, partial key. For each 1:1 relationship set, add a foreign key to one of the entity sets involved in the relationship (a foreign key to the other entity in the relationship)*. For each 1:N relationship set, add a foreign key to the entity set on the N-side of the relationship (to reference the entity set on the 1-side of the relationship)*. * Unless relationship set has attributes. If it does, create a new table for the relationship set. ER to Tables, Method 1 For each M:N relationship set, create a new table. Include a foreign key for each participant entity set, in the relationship set. The key for the new table is the set of all such foreign keys. For each multi-valued attribute, construct a separate table. Repeat the key for the entity in this new table. It will serve as a foreign key to the original table for the entity. The new key of the table will be the key of the entity plus the attribute. This algorithm from Elmasri & Navathe, Fundamentals of Database Systems 17 18 ER to Tables, Method 2 (Book) ER to Tables, Method 2 (Book) For regular entities and relationships (not weak/identifying) Create a table for each entity; include all attributes Create a table for each relationship; include attributes to represent the key for every participant in the relationship. Not mentioned in the book (but important): Choose the key for each table. Easy for tables for entities Not as easy for tables that represent relationships For a weak entity and the identifying relationship Table for the weak entity must include the key from the strong entity in the identifying relationship (plus all attributes directly in the weak entity) Identifying relationships do NOT need tables. Other relationships involving the weak entity must use the concatenation of the partial key for the weak entity plus the key from the corresponding strong entity. The key for the weak entity must be the partial key, plus the key of the corresponding strong entity. 19 20 5

ER to Tables, Method 2 (Book) Then combine tables If you have two or more tables with the same key then combine them into one table. What s happening is that if the entity participates in a relationship where there is at most one of the other entity, the relationship can be represented as a foreign key. Embedded SQL: What and Why? Embedded SQL allows data from a DBMS to be accessed programmatically Embedded SQL Programmers can: Control how data is presented to users Control what data is visible to users Generate SQL dynamically based on user inputs 21 22 When are Queries Analyzed? Static Case At compile time: Static SQL At run time: Dynamic SQL SQL commands are embedded in program with some kind of special delimiters Use a pre-processor that recognizes the SQL parts of the program Prepare once, execute many times Need a way to pass parameters to query Know schema of the result of a SELECT statement in advance 23 24 6

Dynamic Case Create a string at run time that represents the query Use function calls or methods to pass the string to the DBMS (no preprocessing of program) Analyze and execute the query each time Need a way to discover the schema of the result Note: Some languages support both static and dynamic cases Embedded SQL SQL commands can be called from within a host language (e.g., C/C++, Basic,.NET, PHP) program. SQL statements can refer to host variables (including special variables used to return status). Must include a statement to connect to the right database. SQL relations are (multi-) sets of records, with no a priori bound on the number of records. No such data structure in most languages. SQL supports a mechanism called a cursor to handle this. 25 26 Cursors Embedded SQL Implementations Can declare a cursor on a table or query statement (which generates a table). Can open a cursor, and repeatedly fetch a row (then move the cursor), until all rows have been retrieved. May also be possible to modify/delete row pointed to by a cursor. Cursor can report conditions (e.g., end of rows) We will discuss four implementations of Embedded SQL C (Pro*C from Oracle is an example) Java (Using JDBC) C#.NET (Using ADO to talk to MS Access) Scripting (Using PHP & PostgreSQL) Illustrates database-backed web pages. 27 28 7

Example Table Schema Imagine we are tracking products and categories for a retailer Products(int ProductID, int CategoryID, String ProductName, currency UnitPrice) Categories(int CategoryID, String CategoryName) Cursor that gets the name and unit price of all beverages DECLARE pinfo CURSOR FOR SELECT P.ProductName, P.UnitPrice FROM Products P, Categories C WHERE C.CategoryName= Beverages AND P.CategoryID=C.CategoryID ORDER BY P.UnitPrice; OPEN pinfo; FETCH pinfo INTO :p-name, :p-price; (probably for each row) CLOSE pinfo; 29 30 Embedding SQL in C: An Example Embedding SQL in C: (continued) void ListProducts(short Max) { char SQLSTATE[6]; EXEC SQL BEGIN DECLARE SECTION char ProductName[20]; float ProductPrice; short MaxPrice = Max; EXEC SQL END DECLARE SECTION EXEC SQL DECLARE pinfo CURSOR FOR SELECT P.ProductName, P.UnitPrice FROM Products P, Categories C WHERE C.CategoryName="Beverages" AND P.UnitPrice < :MaxPrice AND P.CategoryID=C.CategoryID ORDER BY P.UnitPrice; DECLARE pinfo CURSOR defines a name for this query for later use SQLSTATE holds the return value can tell if more results, among other things EXEC SQL denotes embedded SQL section flag for preprocessor SELECT P.ProductName is our SQL that we want results on < :MaxPrice - Note the use of a variable, defined earlier DECLARE SECTION binds variables into SQL 31 32 8

Embedding SQL in C: (continued) EXEC SQL OPEN pinfo; EXEC SQL FETCH pinfo INTO :ProductName, :ProductPrice; while (SQLSTATE!= "02000") { printf("%s costs %f each\n", ProductName, ProductPrice); EXEC SQL FETCH pinfo INTO :ProductName, :ProductPrice; }; EXEC SQL CLOSE pinfo; OPEN pinfo opens the query we are interested in FETCH pinfo INTO assigns data into our variables, for use in the output ProductName Use of our variable in and out of SQL EXEC CLOSE pinfo We re done with the cursor, free up its resources Embedded SQL in Java Exposed through libraries called JDBC (Java DataBase Connectivity Using package java.sql.* All of the principles of cursors still apply They are now encapsulated in object methods A Java Cursor is called a ResultSet Object Column names and positions are stored in a ResultSetMetaData object 33 34 Embedded SQL in Java Embedding SQL in Java: An Example try { Connection connect = DriverManager.getConnection( jdbc:mysql: www.mydomain.com:12543/mydb, username, password); boolean status = st.execute ( SELECT * FROM Products ); if (status) { ResultSet rset = st.getresultset (); ResultSetMetaData meta = rset.getmetadata (); do stuff } else { query did not return rows } Statement st = connect.createstatement (); } catch (Exception e) { exception thrown because connection failed } rset The Cursor Object (Recordset) meta the collection of columns and column positions for the records else the query may have been an insert, update, delete command 35 36 9

Metadata and ResultSet Objects Embedding SQL in Java: An Example (continued) int ncolumns = meta.getcolumncount(); String columnname = meta.getcolumnlabel(i); int columnwidth = meta.getcolumndisplaysize(i); rset.close (); connect.close (); while (rset.next ()) { Object val = rset.getobject (i); // getstring, getboolean, etc. rset.updateobject (i, obj); // updatestring, updateboolean, etc. } Don t forget to free up resources (result sets, connections) 37 38 Embedded SQL in.net Embedded SQL in.net (C#) Exposed through the libraries System.Data.* We ll focus on System.Data.OleDb Can be used in the Microsoft.NET framework (Basic, C#, Managed C++, JScript) We ll use C# Object-Oriented A Cursor is a OleDbDataReader Object LINQ is another technology for connecting to data sources OleDbCommand mycmd = new OleDbCommand ("SELECT P.ProductName, P.UnitPrice " + "FROM Products P, Categories C " + "WHERE P.CategoryID=C.CategoryID " + "AND C.CategoryName = \"Beverages\" " + "ORDER BY P.UnitPrice", myconn); OleDbDataReader myrdr = mycmd.executereader(); Object name = myrdr.getvalue(0); myrdr.close(); 39 40 10

Embedded SQL in.net (C#): An Example void ListProducts(int MaxPrice) OleDbCommand mycmd = new OleDbCommand(); try { mycmd.connection = new OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=products.mdb"); mycmd.connection.open(); ListProducts(int MaxPrice) definition of this subroutine mycmd The Command object to execute the SQL new OleDb Connection Opens the Access Database products.mdb mycmd.connection Assigns a connection to the command Embedded SQL in.net (C#): An Example (continued) mycmd.commandtext = "SELECT P.ProductName, P.UnitPrice " + "FROM Products P, Categories C " + "WHERE P.UnitPrice < " + MaxPrice + " AND C.CategoryName = \"Beverages\" " + " AND P.CategoryID = C.CategoryID " + "ORDER BY P.UnitPrice"; OleDbDataReader myrdr = mycmd.executereader(); mycmd.commandtext Assign the desired SQL query myrdr = mycmd.executereader() Open a cursor on the SQL "P.UnitPrice < " + MaxPrice - Use a variable defined in C# 41 42 Embedded SQL in.net (C#): An Example (continued) Embedded SQL in.net (C#): An Example (continued) while (myrdr.read()) { Console.WriteLine(myRdr.GetString(0) + " costs $" + myrdr.getdecimal(1) + " each ); } catch (Exception ex) { Console.WriteLine(ex.Message); } } //end try while (myrdr.read()) Read gets the next record. If it s after the last record, Read() returns False myrdr.get***** - OleDbDataReader provides many Get functions to retrieve different data types. GetFieldType() returns the types for each attribute, if they are not already known catch catches any exception that is thrown during execution Message is a member of the Exception object. Console.WriteLine Write to the command window 43 44 11

Embedded SQL using PostgreSQL and PHP Scripting languages such as Perl, Python, and PHP have database support We ll talk some about PHP next time To work with a PostgreSQL database in a scripting language, you must use a set of functions designed to communicate with PostgreSQL PHP includes the PostgreSQL functions - you do not need an additional library Other Embedded SQL Solutions ODBC Open Database Connectivity Old standard, proposed by Microsoft but driven by the database community Many vendors, including Oracle, make ODBC drivers available Haskell HaskellDB (currently uses ADO) Cursors are first-class objects (each attribute is a type) LINQ (Language-Integrated Query) 45 46 LINQ for C#: Define Local Objects Can Use SQL-Like Syntax in C# [Table(Name= Categories")] public class Category { [Column(IsPrimaryKey=true)] public int CategoryID; [Column] public string CategoryName; } // DataContext takes a connection string DataContext db = new DataContext("c:\\productdb\\productdb.mdf"); // Get a typed table to run queries Table<Category> Cats = db.gettable<category>(); // Query for beverage category var q = from c in Cats where c.categoryname == beverage" select c; foreach (var cat in q) Console.WriteLine("id = {0}, Category = {1}", cat.categoryid, cat.categoryname); 47 48 12