1 Lecture 8: SQL Programming and Transactions Friday, January 24, 2003.

Slides:



Advertisements
Similar presentations
What is Concurrent Process (CP)? Multiple users access databases and use computer systems Multiple users access databases and use computer systems simultaneously.
Advertisements

Transaction Program unit that accesses the database
Transactions - Concurrent access & System failures - Properties of Transactions - Isolation Levels 4/13/2015Databases21.
1 Lecture 11: Transactions: Concurrency. 2 Overview Transactions Concurrency Control Locking Transactions in SQL.
Transactions (Chapter ). What is it? Transaction - a logical unit of database processing Motivation - want consistent change of state in data Transactions.
Information Systems Chapter 4 Relational Databases Modelling.
ICOM 6005 – Database Management Systems Design Dr. Manuel Rodríguez-Martínez Electrical and Computer Engineering Department Lecture 16 – Intro. to Transactions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
Concurrency Control and Recovery In real life: users access the database concurrently, and systems crash. Concurrent access to the database also improves.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #15 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #16 M.P. Johnson Stern School of Business, NYU Spring, 2005.
Concurrency control using transactions 1Transactions.
Transactions and Wrap-Up Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems December 8, 2005 Some slide content derived.
End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004.
1 Transaction Management Overview Yanlei Diao UMass Amherst March 15, 2007 Slides Courtesy of R. Ramakrishnan and J. Gehrke.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
1 A Closer Look Chapter 2. 2 Underlying Concepts of Databases and Transaction Processing.
Dec 15, 2003Murali Mani Transactions and Security B term 2004: lecture 17.
Cs3431 Transactions, Logging and Security. cs3431 Transactions: What and Why? A set of operations on a database must appear as one “unit”. Example: Consider.
Programs with SQL Host language + Embedded SQL Preprocessor Host Language + function calls Host language compiler Host language program Preprocessor Host.
Embedded SQL Direct SQL is rarely used: usually, SQL is embedded in some application code. We need some method to reference SQL statements. But: there.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
COMP 5138 Relational Database Management Systems Semester 2, 2007 Lecture 8A Transaction Concept.
Transaction Management and Concurrency Control
Lecture 9: Conceptual Database Design January 27 th, 2003.
INTRODUCTION TO TRANSACTION PROCESSING CHAPTER 21 (6/E) CHAPTER 17 (5/E)
Database Design April 3, Projects, More Details Goal: build a DB application. (almost) anything goes. Groups of 3-4. End of week 2: groups formed.
© D. Wong 2002 © D. Wong CS610 / CS710 Database Systems I Daisy Wong.
1 CSE 480: Database Systems Lecture 23: Transaction Processing and Database Recovery.
Concurrency Control and Recovery In real life: users access the database concurrently, and systems crash. Concurrent access to the database also improves.
Transactions1 Unit of work on a database. Transactions2 Transactions, concept Logical unit of work on the database –Examples Transfer money from bank.
SQL in a Programming Environment - Part II CIS 4301 Lecture Notes Lecture /4/2006.
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
Database Management Systems, 2 nd Edition. R. Ramakrishnan and J. Gehrke1 Transaction Management Overview Lecture 21 Ramakrishnan - Chapter 18.
1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.
Transaction processing Book, chapter 6.6. Problem: With a single user…. you run a query, you get the results, you run the next, etc. But database life.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 136 Database Systems I SQL Modifications and Transactions.
Phase 2, Answering queries using views. February 2 nd, 2004.
SQL in a Programming Environment CIS 4301 Lecture Notes Lecture /11/2006.
Conceptual Database Design. Building an Application with a DBMS Requirements modeling (conceptual, pictures) –Decide what entities should be part of the.
1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.
Sekolah Tinggi Ilmu Statistik (STIS) 1 Dr. Said Mirza Pahlevi, M.Eng.
Database Design Why do we need it? – Agree on structure of the database before deciding on a particular implementation. Consider issues such as: –What.
ICS 321 Fall 2011 The Database Language SQL (iv) Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 10/26/20111Lipyeow.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
Transactions. Transaction: Informal Definition A transaction is a piece of code that accesses a shared database such that each transaction accesses shared.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_JDBC_MySQL 1 Transations.
Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT.
1 Advanced Database Concepts Transaction Management and Concurrency Control.
1 Transactions Serializability Isolation Levels Atomicity.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
3 Database Systems: Design, Implementation, and Management CHAPTER 9 Transaction Management and Concurrency Control.
10 1 Chapter 10 - A Transaction Management Database Systems: Design, Implementation, and Management, Rob and Coronel.
ICOM 6005 – Database Management Systems Design Dr. Manuel Rodríguez-Martínez Electrical and Computer Engineering Department Lecture 16 – Intro. to Transactions.
1 Lecture 14: Transactions in SQL Wednesday, February 8, 2006.
1 Transaction Processing Case Study. 2 Interaksi Proses There is table Sells(shop,beverage,price), and suppose that Joe’s Shop sells only Juice for $2.50.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
SQL Environment.
Lecture 5: Conceptual Database Design
Database Design Why do we need it? Consider issues such as:
Conceptual Database Design
Transactions Properties.
Transaction Properties
Lecture 06: SQL Systems Aspects
Lecture 17: Systems Aspects of SQL
Lecture 13: Transactions in SQL
Lecture 06: SQL Monday, October 11, 2004.
Lecture 14: XML Publishing & Storage
Lecture 05: SQL Systems Aspects
Lecture 11: Transactions in SQL
Presentation transcript:

1 Lecture 8: SQL Programming and Transactions Friday, January 24, 2003

2 Impedance Mismatch Example: SQL in C: –C uses int, char[..], pointers, etc –SQL uses tables Impedance mismatch = incompatible types

3 The Impedance Mismatch Problem Why not use only one language? Forgetting SQL: “we can quickly dispense with this idea” [textbook, pg. 351]. SQL cannot do everything that the host language can do. Solution: use cursors

4 Interface: SQL / Host Language Values get passed through shared variables. Colons precede shared variables when they occur within the SQL statements. EXEC SQL: precedes every SQL statement in the host language. The variable SQLSTATE provides error messages and status reports (e.g., “00000” says that the operation completed with no problem). EXEC SQL BEGIN DECLARE SECTION; char productName[30]; EXEC SQL END DECLARE SECTION; EXEC SQL BEGIN DECLARE SECTION; char productName[30]; EXEC SQL END DECLARE SECTION;

5 Example Product (pname, price, quantity, maker) Purchase (buyer, seller, store, pname) Company (cname, city) Person(name, phone, city)

6 Using Shared Variables Void simpleInsert() { EXEC SQL BEGIN DECLARE SECTION; char n[20], c[30];/* product-name, company-name */ int p, q;/* price, quantity */ char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; /* get values for name, price and company somehow */ EXEC SQL INSERT INTO Product(pname, price, quantity, maker) VALUES (:n, :p, :q, :c); } Void simpleInsert() { EXEC SQL BEGIN DECLARE SECTION; char n[20], c[30];/* product-name, company-name */ int p, q;/* price, quantity */ char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; /* get values for name, price and company somehow */ EXEC SQL INSERT INTO Product(pname, price, quantity, maker) VALUES (:n, :p, :q, :c); }

7 Cursors 1.Declare the cursor 2.Open the cursor 3.Fetch tuples one by one 4.Close the cursor

8 Cursors void product2XML() { EXEC SQL BEGIN DECLARE SECTION; char n[20], c[30]; int p, q; char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; EXEC SQL DECLARE crs CURSOR FOR SELECT pname, price, quantity, maker FROM Product; EXEC SQL OPEN crs;

9 Cursors printf(“ \n”); while (1) { EXEC SQL FETCH FROM crs INTO :n, :p, :q, :c; if (NO_MORE_TUPLES) break; printf(“ \n”); printf(“ %s \n”, n); printf(“ %d \n”, p); printf(“ %d \n”, q); printf(“ %s \n”, c); printf(“ \n”); } EXECT SQL CLOSE crs; printf(“ \n”); }

10 What is NO_MORE_TUPLES ? #define NO_MORE_TUPLES !(strcmp(SQLSTATE,”02000”))

11 More on Cursors cursors can modify a relation as well as read it. We can determine the order in which the cursor will get tuples by the ORDER BY keyword in the SQL query. Cursors can be protected against changes to the underlying relations. The cursor can be a scrolling one: can go forward, backward +n, -n, Abs(n), Abs(-n).

12 In JDBC public void doIt(){ try { Class.forName("com.ms.jdbc.odbc.JdbcOdbcDriver"); java.sql.Connection c = DriverManager.getConnection("jdbc:odbc:cse444","cse444","cse4 44"); java.sql.Statement s= c.createStatement(); java.sql.ResultSet rs; rs = s.executeQuery("Select * from beers"); java.sql.ResultSetMetaData md = rs.getMetaData(); while (rs.next()){ area.append("\nTUPLE: |"); for (int i = 1; i <= md.getColumnCount();i++){ area.append(rs.getString(i) + " | "); } } rs.close(); } catch (Exception e){ e.printStackTrace(); System.out.println("something went wrong in database land"); } }

13 Transactions Address two issues: Access by multiple users –Remember the “client-server” architecture: one server with many clients Protection against crashes

14 Flight Reservation get values for :flight, :date, :seat EXEC SQL SELECT occupied INTO :occ FROM Flight WHERE fltNum = :flight AND fltdt= :date AND fltSeat=:seat if (!occ) { EXEC SQL UPDATE Flights SET occupied = ‘true’ WHERE fltNum= :flight AND fltdt= :date AND fltSeat=:seat /* more code missing */ } else /* notify customer that seat is not available */

15 Problem #1 Customer 1 - finds a seat empty Customer 2 - finds the same seat empty Customer 1 - reserves the seat. Customer 2 - reserves the seat. Customer 1 will not be happy. serializability

16 Bank Transfers Transfer :amount from :account1 to :account2 EXEC SQL SELECT balance INTO :balance1 FROM Accounts WHERE accNo = :account1 if (balance1 >= amount) EXEC SQL UPDATE Accounts SET balance = balance + :amount WHERE acctNo = :account2; EXEC SQL UPDATE Accounts SET balance = balance - :amount WHERE acctNo = :account1; Crash...

17 Transactions The user/programmer can group a sequence of commands so that they are executed atomically and in a serializable fashion: Transaction commit: all the operations should be done and recorded. Transaction abort: none of the operations should be done. In SQL: EXEC SQL COMMIT; EXEC SQL ROLLBACK; Easier said than done...

18 ACID ACID Properties A Atomicity: all actions of a transaction happen, or none happen. C Consistency: if a transaction is consistent, and the database starts from a consistent state, then it will end in a consistent state. I Isolation: the execution of one transaction is isolated from other transactions. D Durability: if a transaction commits, its effects persist in the database.

19 How Do We Assure ACID? Concurrency control: Guarantees consistency and isolation, given atomicity. Logging and Recovery: Guarantees atomicity and durability. If you are going to be in the logging business, one of the things that you’ll have to do is learn about heavy equipment. -- Robert VanNatta Logging History of Columbia County

20 Transactions in SQL In “ad-hoc” SQL: –Default: each statement = one transaction In “embedded” SQL: BEGIN TRANSACTION [SQL statements] COMMIT or ROLLBACK (=ABORT)

21 Transactions: Serializability Serializability = the technical term for isolation An execution is serial if it is completely before or completely after any other transaction’s execution An execution is serializable if it equivalent to one that is serial DBMS can offer serializability guarantees

22 Serializability Enforced with locks, like in Operating Systems ! But this is not enough: LOCK A [write A=1] UNLOCK A LOCK B [write B=2] UNLOCK B LOCK A [write A=1] UNLOCK A LOCK B [write B=2] UNLOCK B LOCK A [write A=3] UNLOCK A LOCK B [write B=4] UNLOCK B LOCK A [write A=3] UNLOCK A LOCK B [write B=4] UNLOCK B User 1 User 2 What is wrong ? time

23 Serializability Solution: two-phase locking –Lock everything at the beginning –Unlock everything at the end Read locks: many simultaneous read locks allowed Write locks: only one write lock allowed Insert locks: one per table

24 Isolation Levels in SQL 1.“Dirty reads” SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 2.“Committed reads” SET TRANSACTION ISOLATION LEVEL READ COMMITTED 3.“Repeatable reads” SET TRANSACTION ISOLATION LEVEL REPEATABLE READ 4.Serializable transactions (default): SET TRANSACTION ISOLATION LEVEL SERIALIZABLE Reading assignment: chapter 8.6

25 Database Design Entity Relationship Diagrams

26 Building an Application with a DBMS Requirements modeling (conceptual, pictures) –Decide what entities should be part of the application and how they should be linked. Schema design and implementation –Decide on a set of tables, attributes. –Define the tables in the database system. –Populate database (insert tuples). Write application programs using the DBMS –way easier now that the data management is taken care of.

27 Database Design Why do we need it? – Agree on structure of the database before deciding on a particular implementation. Consider issues such as: –What entities to model –How entities are related –What constraints exist in the domain –How to achieve good designs

28 Database Design Formalisms 1. Object Definition Language (ODL): – Closer in spirit to object-oriented models 2. Entity/Relationship model (E/R): –More relational in nature. Both can be translated (semi-automatically) to relational schemas ODL to OO-schema: direct transformation (C++ or Smalltalk based system).