Chapter 8 Using SQL in an Application. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-2 CSC 4480 outline Intro (3-9) Static SQL (10-11)

Slides:



Advertisements
Similar presentations
Copyright  Oracle Corporation, All rights reserved. 2 Java and Databases: An Overview.
Advertisements

CSC343 – Introduction to databases – A. Vaisman1 Database Application Development.
Objective: To access a database from an application program (as opposed to interactive interfaces) Why? An interactive interface is convenient but not.
1 Combining SQL and Conventional Programming Languages Source: slides by Jeffrey Ullman.
Embedded SQL John Ortiz. Lecture 15Embedded SQL2 Why Isn’t Interactive SQL Enough?  How to do this using interactive SQL?  Print a well-formatted transcript.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
1 SQL in the Real World Chapter Interactive vs. Non-Interactive SQL Interactive SQL: SQL statements input from terminal; DBMS outputs to screen.
Distributed Application Development B. Ramamurthy.
Murali Mani SQL with other Programming Languages.
End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004.
1 JDBC Java Database Connectivity. 2 c.pdf
SPRING 2004CENG 3521 SQL: Constraints, Triggers, Embedded SQL Chapters: 5, 6.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
EmbeddedSQL: 1 Impedance Mismatch Problem Problem : How to connect SQL statements with conventional programming languages Different models of language.
Winter 2002Arthur Keller – CS 18011–1 Schedule Today: Feb. 7 (TH) u PL/SQL, Embedded SQL, CLI, JDBC. u Read Sections 8.1, Feb. 12 (T) Advising.
SEMESTER 1, 2013/2014 DB2 APPLICATION DEVELOPMENT OVERVIEW.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 Section 6 Embedded SQL. 6-2 CA306 Embedded SQL Section Content 6.1Embedded SQL 6.2Java Database Connectivity 6.3Web Databases.
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
Chapter 8 Using SQL in an Application. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-2 Interactive vs. Non-Interactive SQL Interactive.
Overview of JDBC and Pro*C 1 Overview of JDBC,Pro*C and Oracle connectivity on Omega CSE 5330 – Database Systems.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke; edited K. Shomper1 Database Application Development Chapter 6.
Announcements Read JDBC Project Step 5, due Monday.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 9- 1 DATADABASE PROGRAMMING 2Chapter 13 from our text.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui COMP 302 Database Systems Java Data Base Connectivity Lecturer Dr Pavle Mogin.
CS 405G: Introduction to Database Systems Database programming.
Overview of JDBC and Pro*C 1 CSE 5330 – Database Systems.
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
Dr Gordon Russell, Napier University Unit Embedded SQL - V3.0 1 Embedded SQL Unit 5.1.
Advanced SQL: Cursors & Stored Procedures
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Winter 2006 Keller, Ullman, Cushing 11–1 Embedded SQL Add to a conventional programming language (C in our examples) certain statements that represent.
ICS 321 Fall 2010 SQL in a Server Environment (i) Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 11/1/20101Lipyeow.
Programmatic SQL Shaista Khan CS 157B. Topic Embedded SQL statements in high-level programming languages.
SQL in a Programming Environment CIS 4301 Lecture Notes Lecture /11/2006.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 6 MORE SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
1 CS 430 Database Theory Winter 2005 Lecture 14: Additional SQL Topics.
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Application Development Chapter 6 Sections –
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
Dr Gordon Russell, Napier University Unit Embedde SQL - V2.0 1 Embedded SQL Unit 5.1.
Chapter 4 An Introduction to SQL. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.4-2 Topics in this Chapter SQL: History and Overview The.
1 Database Application Development Chapter 6 Sections –
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
SCU Fall 2002JoAnne Holliday10–1 Schedule Today u Triggers, Procedures, PL/SQL. u Read Sections , 8.1, 8.5. Next u Transaction concepts, security.
Lu Wei1 Outline Introduction Basic SQL Setting Up and Using PostgreSQL Advanced SQL Embeded SQL.
1 JDBC – Java Database Connectivity CS , Spring 2010.
6/9/2016CENG 352 Database Management Systems1 SQL in the Real World.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
SQL in the real world 1. The Three-Tier Architecture of Database Applications browser network HTTP Web server Application server Database server database.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Application Development Chapter 6.
Chapter 4 An Introduction to SQL. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.4-2 Topics in this Chapter SQL: History and Overview The.
Instructor: Jinze Liu Fall /8/2016Jinze University of Kentucky 2 Database Project Database Architecture Database programming.
Chapter 4 An Introduction to SQL.
1st Semester, 2017 Sanghyun Park
Introduction to SQL Programming Techniques
SQL Environment.
Web Technologies IT230 Dr Mohamed Habib.
Chapter 5: Advanced SQL Database System concepts,6th Ed.
CPSC-310 Database Systems
Database Application Development
DB Programming: SQL Programming Techniques
Java Database Connectivity
Chapter 8 Advanced SQL.
Lecture 05: SQL Systems Aspects
Presentation transcript:

Chapter 8 Using SQL in an Application

Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-2 CSC 4480 outline Intro (3-9) Static SQL (10-11) General (12-17) Stored Procedures (18-22) JDBC (23-31) ODBC (32)

Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-3 Interactive vs. Non-Interactive SQL Interactive SQL: SQL statements input from terminal; DBMS outputs to screen –Inadequate for most uses It may be necessary to process the data before output Amount of data returned not known in advance SQL has very limited expressive power (not Turing- complete) Non-interactive SQL: SQL statements are included in an application program written in a host language, like C, Java, COBOL

Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-4 Application Program Host languageHost language: A conventional language (e.g., C, Java) that supplies control structures, computational capabilities, interaction with physical devices SQL: supplies ability to interact with database. Using the facilities of both: the application program can act as an intermediary between the user at a terminal and the DBMS

Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-5 Preparation Before an SQL statement is executed, it must be prepared by the DBMS: –What indices can be used? –In what order should tables be accessed? –What constraints should be checked? Decisions are based on schema, table sizes, etc. Result is a query execution plan Preparation is a complex activity, usually done at run time, justified by the complexity of query processing

Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-6 Introducing SQL Into the Application SQL statements can be incorporated into an application program in two different ways: –Statement Level Interface (SLI): Application program is a mixture of host language statements and SQL statements and directives –Call Level Interface (CLI): Application program is written entirely in host language SQL statements are values of string variables that are passed as arguments to host language (library) procedures

Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-7 Statement Level Interface SQL statements and directives in the application have a special syntax that sets them off from host language constructs –e.g., EXEC SQL SQL_statement Precompiler scans program and translates SQL statements into calls to host language library procedures that communicate with DBMS Host language compiler then compiles program

Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-8 Statement Level Interface SQL constructs in an application take two forms: –Standard SQL statements (static or embedded SQL): Useful when SQL portion of program is known at compile time –Directives (dynamic SQL): Useful when SQL portion of program not known at compile time. Application constructs SQL statements at run time as values of host language variables that are manipulated by directives Precompiler translates statements and directives into arguments of calls to library procedures.

Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-9 Call Level Interface Application program written entirely in host language (no precompiler) –Examples: JDBC, ODBC SQL statements are values of string variables constructed at run time using host language –Similar to dynamic SQL Application uses string variables as arguments of library routines that communicate with DBMS –e.g. executeQuery (“ SQL query statement ”)

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Static SQL Declaration section for host/SQL communication Colon convention for value ( WHERE ) and result ( INTO ) parameters EXEC SQL BEGIN DECLARE SECTION ; unsigned long num_enrolled; char crs_code; char SQLSTATE [6]; EXEC SQL END DECLARE SECTION ; ………. EXEC SQL SELECT C.NumEnrolled INTO :num_enrolled Course FROM Course C WHERE C.CrsCode = :crs_code; Variables shared by host and SQL “:” used to set off host variables

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Status EXEC SQL SELECT C.NumEnrolled INTO :num_enrolled Course FROM Course C WHERE C.CrsCode = :crs_code; if ( !strcmp ( SQLSTATE, “00000”) ) { printf ( “statement failed” ) }; In parameter Out parameter

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Connections To connect to an SQL database, use a connect statement CONNECT TO database_name AS connection_name USING user_id

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Transactions No explicit statement is needed to begin a transaction –A transaction is initiated when the first SQL statement that accesses the database is executed The mode of transaction execution can be set with SET TRANSACTION READ ONLY ISOLATION LEVEL SERIALIZABLE Transactions are terminated with COMMIT or ROLLBACK statements

8-14 Example: Course Deregistration EXEC SQL CONNECT TO :dbserver; if ( ! strcmp ( SQLSTATE, “00000”) ) exit (1); ….. Transcript EXEC SQL DELETE FROM Transcript T WHERE T.StudId = :studid AND T.Semester = ‘S2000’ AND T.CrsCode = :crscode; if (! strcmp ( SQLSTATE, “00000”) ) EXEC SQL ROLLBACK; else { Course EXEC SQL UPDATE Course C SET C.Numenrolled = C.Numenrolled – 1 WHERE C.CrsCode = :crscode; if (! strcmp ( SQLSTATE, “00000”) ) EXEC SQL ROLLBACK ; else EXEC SQL COMMIT ; }

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Buffer Mismatch Problem, aka Impedance Mismatch Problem Problem: SQL deals with tables (of arbitrary size); host language program deals with fixed size buffers –How is the application to allocate storage for the result of a SELECT statement? Solution: Fetch a single row at a time –Space for a single row (number and type of out parameters) can be determined from schema and allocated in application

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Cursors Result set – set of rows produced by a SELECT statement Cursor – pointer to a row in the result set. Cursor operations: –Declaration –Open – execute SELECT to determine result set and initialize pointer –Fetch – advance pointer and retrieve next row –Close – deallocate cursor

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Cursors (cont’d) SELECT cursor Base table Result set (or pointers to it) application

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Stored Procedures (eg, PL/SQL in Oracle) Procedure – written in a conventional algorithmic language –Included as schema element (stored in DBMS) –Invoked by the application Advantages: –Intermediate data need not be communicated to application (time and cost savings) –Procedure’s SQL statements prepared in advance –Authorization can be done at procedure level –Added security since procedure resides in server –Applications that call the procedure need not know the details of database schema – all database access is encapsulated within the procedure

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Stored Procedures Call P P In/out arguments Application (client) P Intermediate results DBMS (server) Network connection table Regular procedure Stored procedure

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Stored Procedures CREATE PROCEDURE CREATE PROCEDURE Register (char :par1, char :par2) AS BEGIN EXEC SQL SELECT ……. ; IF ( ……) THEN …… -- SQL embedded in ELSE …. -- Persistent Stored Modules -- (PSM) language END EXECUTE PROCEDURE EXEC SQL EXECUTE PROCEDURE Register ( :crscode, :studid); Schema : Application :

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Integrity Constraint Checking Transaction moves database from an initial to a final state, both of which satisfy all integrity constraints but... –Constraints might not be true of intermediate states hence … –Constraint checks at statement boundaries might be inappropriate SQL (optionally) allows checking to be deferred to transaction COMMIT

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Deferred Constraint Checking Schema : NumberEnrolled CREATE ASSERTION NumberEnrolled CHECK ( …….) DEFERRABLE DEFERRABLE; Application : NumberEnrolled DEFERRED SET CONSTRAINT NumberEnrolled DEFERRED; Transaction is aborted if constraint is false at commit time

Copyright © 2005 Pearson Addison-Wesley. All rights reserved JDBC Call-level interface (CLI) for executing SQL from a Java program SQL statement is constructed at run time as the value of a Java variable (as in dynamic SQL) JDBC passes SQL statements to the underlying DBMS. Can be interfaced to any DBMS that has a JDBC driver Part of SQL:2003

Copyright © 2005 Pearson Addison-Wesley. All rights reserved JDBC Run-Time Architecture DBMS application driver manager DB/2 driver SQLServer driver Oracle driver DB/2 database SQLServer database Oracle database

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Executing a Query import java.sql.*; -- import all classes in package java.sql Class.forName (driver name); // static method of class Class // loads specified driver Connection con = DriverManager.getConnection(Url, Id, Passwd); Static method of class DriverManager; attempts to connect to DBMS If successful, creates a connection object, con, for managing the connection Statement stat = con.createStatement (); Creates a statement object stat Statements have executeQuery() method

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Executing a Query (cont’d) Transcript String query = “SELECT T.StudId FROM Transcript T” + “WHERE T.CrsCode = ‘cse305’ ” + “AND T.Semester = ‘S2000’ ”; ResultSet res = stat.executeQuery (query); Creates a result set object, res. Prepares and executes the query. Stores the result set produced by execution in res (analogous to opening a cursor). The query string can be constructed at run time (as above). The input parameters are plugged into the query when the string is formed (as above)

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Transcript String query = “SELECT T.StudId FROM Transcript T” + “WHERE T.CrsCode = ? AND T.Semester = ?”; PreparedStatement ps = con.prepareStatement ( query ); Prepares the statement Creates a prepared statement object, ps, containing the prepared statement Placeholdersin Placeholders (?) mark positions of in parameters; special API is provided to plug the actual values in ? positions indicated by the ?’s Preparing and Executing a Query placeholders

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Preparing and Executing a Query (cont’d) String crs_code, semester; ……… in ps.setString(1, crs_code); // set value of first in parameter in ps.setString(2, semester); // set value of second in parameter ResultSet res = ps.executeQuery ( ); Creates a result set object, res Executes the query Stores the result set produced by execution in res while ( res.next ( ) ) { // advance the cursor j = res.getInt (“StudId”); // fetch output int-value …process output value… }

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Result Sets and Cursors Three types of result sets in JDBC: –Forward-only: not scrollable –Scroll-insensitive: scrollable; changes made to underlying tables after the creation of the result set are not visible through that result set –Scroll-sensitive: scrollable; updates and deletes made to tuples in the underlying tables after the creation of the result set are visible through the set

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Result Set Any result set type can be declared read-only or updatable – CONCUR_UPDATABLE (assuming SQL query satisfies the conditions for updatable views) UpdatableUpdatable: Current row of an updatable result set can be changed or deleted, or a new row can be inserted. Any such change causes changes to the underlying database table Statement stat = con.createStatement ( ResultSet. TYPE_SCROLL_SENSITIVE, ResultSet. CONCUR_UPDATABLE ); res.updateString (“Name”, “John” ); // change the attribute “Name” of // current row in the row buffer. res.updateRow ( ); // install changes to the current row buffer // in the underlying database table

Copyright © 2005 Pearson Addison-Wesley. All rights reserved Handling Exceptions try/catch is the basic structure within which an SQL statement should be embedded If an exception is thrown, an exception object, ex, is created and the catch clause is executed The exception object has methods to print an error message, return SQLSTATE, etc. try {...Java/JDBC code... } catch ( SQLException ex ) { …exception handling code... }

Copyright © 2005 Pearson Addison-Wesley. All rights reserved ODBC Call level interface that is database independent Related to SQL/CLI, part of SQL:1999 Software architecture similar to JDBC with driver manager and drivers Not object oriented Low-level: application must specifically allocate and deallocate storage