Objective: To access a database from an application program (as opposed to interactive interfaces) Why? An interactive interface is convenient but not.

Slides:



Advertisements
Similar presentations
Stored Procedure Language Stored Procedure Overview Stored Procedure is a function in a shared library accessible to the database server can also write.
Advertisements

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 9 Introduction to SQL Programming Techniques.
CSC343 – Introduction to databases – A. Vaisman1 Database Application Development.
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.
Murali Mani SQL with other Programming Languages.
METU Department of Computer Eng Ceng 302 Introduction to DBMS SQL: Assertions, Views, and Programming Techniques by Pinar Senkul resources: mostly froom.
End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004.
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.
Chapter 9 MORE SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
SEMESTER 1, 2013/2014 DB2 APPLICATION DEVELOPMENT OVERVIEW.
Advanced Database CS-426 Week 2 – Logic Query Languages, Object Model.
Database Applications.  Database Programming  Web databases  Application architecture.
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.
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.
Chapter 9 MORE SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
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.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
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)
Overview of JDBC and Pro*C 1 CSE 5330 – Database Systems.
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
Advanced SQL: Cursors & Stored Procedures
ICS 321 Fall 2009 DBMS Application Programming Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 10/06/20091Lipyeow.
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.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
Chapter 6 MORE SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
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 –
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
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.
Chapter 8 Embedded SQL.
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.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 & 9 SQL-99: SchemaDefinition, Constraints, Introduction to SQL Programming Techniques.
Lu Wei1 Outline Introduction Basic SQL Setting Up and Using PostgreSQL Advanced SQL Embeded SQL.
Chapter 7 SQL HUANG XUEHUA. Chapter Objectives Specification of more general constraints via assertions SQL facilities for defining views (virtual.
6/9/2016CENG 352 Database Management Systems1 SQL in the Real World.
Database Application Development Database Programming Embedded SQL Dynamic SQL Embedded SQL in Java Database APIs: Alternative to embedding Embedded SQL.
SQL- Updates, Assertions and Views. Data Definition, Constraints, and Schema Changes Used to CREATE, DROP, and ALTER the descriptions of the tables (relations)
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Application Development Chapter 6.
10/3/2017.
CSE202 Database Management Systems
Introduction to SQL Programming Techniques
Web Technologies IT230 Dr Mohamed Habib.
Views, Stored Procedures, Functions, and Triggers
Chapter 5: Advanced SQL Database System concepts,6th Ed.
Subject Name: DATABASE MANAGEMENT SYSTEM Subject Code: 10CS54
CPSC-310 Database Systems
CPSC-310 Database Systems
Database Application Development
DB Programming: SQL Programming Techniques
Introduction to SQL Programming Techniques
Unit I-2.
Chapter 8 Advanced SQL.
Information Management
Presentation transcript:

Objective: To access a database from an application program (as opposed to interactive interfaces) Why? An interactive interface is convenient but not sufficient A majority of database operations are made thru application programs Programming Techniques (Ch 9)

Database Programming Approaches Embedded commands: Database commands are embedded in a general- purpose programming language Library of database functions: Available to the host language for database calls; known as an API (Application Programming Interface) A special-purpose language Minimizes impedance mismatch

Impedance Mismatch Incompatibilities between a host programming language and the database model, e.g., type mismatch and incompatibilities; requires a new binding for each language set vs. record-at-a-time processing need special iterators to loop over query results and manipulate individual values

Steps in Database Programming 1.Client program opens a connection to the database server 2.Client program submits queries to and/or updates the database 3.When database access is no longer needed, client program closes (terminates) the connection

Embedded SQL Most SQL statements can be embedded in a general- purpose host programming language such as COBOL, C, Java An embedded SQL statement is distinguished from the host language statements by enclosing it between EXEC SQL or EXEC SQL BEGIN and a matching END-EXEC or EXEC SQL END (or semicolon) Syntax may vary with language Shared variables (used in both languages) usually prefixed with a colon (:) in SQL

Example: Variable Declaration in Language C Variables inside DECLARE are shared and can appear (while prefixed by a colon) in SQL statements int loop; EXEC SQL BEGIN DECLARE SECTION; varchar dname[16], fname[16], …; char ssn[10], bdate[11], …; int dno, dnumber, SQLCODE, …; EXEC SQL END DECLARE SECTION; SQLCODE is used to communicate errors/exceptions between the database and the program

Embedded SQL in C loop = 1; while (loop) { prompt (“Enter SSN: “, ssn); EXEC SQL select FNAME, LNAME, ADDRESS, SALARY into :fname, :lname, :address, :salary from EMPLOYEE where SSN == :ssn; if (SQLCODE == 0) printf(fname, …); else printf(“SSN does not exist: “, ssn); prompt(“More SSN? (1=yes, 0=no): “, loop); }

Embedded SQL in C A cursor (iterator) is needed to process multiple tuples FETCH commands move the cursor to the next tuple CLOSE CURSOR indicates that the processing of query results has been completed EXEC SQL BEGIN DECLARE SECTION; int v1; VARCHAR v2; EXEC SQL END DECLARE SECTION;... EXEC SQL DECLARE foo CURSOR FOR SELECT a, b FROM test;... do {... EXEC SQL FETCH NEXT FROM foo INTO :v1, :v2;... } while (...);

Dynamic SQL Objective: Composing and executing new (not previously compiled) SQL statements at run-time a program accepts SQL statements from the keyboard at run-time Dynamic query can be complex because the type and number of retrieved attributes are unknown at compile time

Dynamic SQL: An Example EXEC SQL BEGIN DECLARE SECTION; varchar sqlupdatestring[256]; EXEC SQL END DECLARE SECTION; … prompt (“Enter update command:“, sqlupdatestring); EXEC SQL PREPARE sqlcommand FROM :sqlupdatestring; EXEC SQL EXECUTE sqlcommand;

Embedded SQL in Java SQLJ: a standard for embedding SQL in Java An SQLJ translator converts SQL statements into Java See east.oracle.com/docs/cd/B10501_01/java.920/a96655/overview.ht m# for a listing of steps involvedhttp://download- east.oracle.com/docs/cd/B10501_01/java.920/a96655/overview.ht m# These are executed thru the JDBC interface Certain classes have to be imported E.g., java.sql See, for example, east.oracle.com/docs/cd/B10501_01/java.920/a96655/toc.htm east.oracle.com/docs/cd/B10501_01/java.920/a96655/toc.htm

Example: Embedded SQL in Java ssn = readEntry("Enter a SSN: "); try { #sql{select FNAME< LNAME, ADDRESS, SALARY into :fname, :lname, :address, :salary from EMPLOYEE where SSN = :ssn}; } catch (SQLException se) { System.out.println("SSN does not exist: ",+ssn); return; } System.out.println(fname + " " + lname + … );

Database Programming using an API Embedded SQL provides static database programming API: Dynamic database programming with a library of functions Advantage: No preprocessor needed Disadvantage: SQL syntax checks to be done at run-time

Java Database Connectivity JDBC: function calls for Java/database interaction A Java program with JDBC functions can access any relational DBMS that has a JDBC driver See, for example, x.html x.html for more details

Steps in JDBC Database Access 1.Import JDBC library (java.sql.*) 2.Load JDBC driver: Class.forname(“oracle.jdbc.driver.OracleDriver”) 3.Define appropriate variables 4.Create a connection object (via getConnection ) 5.Create a statement object from the Statement class: 1. PreparedStatment2. CallableStatement 6.Identify statement parameters (designated by question marks) 7.Bound parameters to program variables 8.Execute SQL statement (referenced by an object) via JDBC’s executeQuery 9.Process query results (returned in an object of type ResultSet) ResultSet is a 2-dimentional table

Java exampleexample Try running in 3D03/3C13 Other resource: java.sun.com/j2se/1.5.0/docs/guide/getstart/GettingStartedTOC.fm.html JDBC Recipes: A Problem-Solution Approach; Mahmoud Parsian; Apress

Database Stored Procedures Persistent procedures/functions (modules) are stored locally and executed by the database server As opposed to execution by clients Advantages: If the procedure is needed by many applications, it can be invoked by any of them (thus reduce duplications) Execution by the server reduces communication costs Disadvantages: Every DBMS has its own syntax and this can make the system less portable (examine help on Stored Procedures for SQL Server)

Stored Procedure Constructs A stored procedure CREATE PROCEDURE procedure-name (params) local-declarations procedure-body; A stored function CREATE FUNCTION fun-name (params) RETRUNS return-type local-declarations function-body; Calling a procedure or function CALL procedure-name/fun-name (arguments);

Example CREATE FUNCTION DEPT_SIZE (IN deptno INTEGER) RETURNS VARCHAR[7] DECLARE TOT_EMPS INTEGER; SELECT COUNT (*) INTO TOT_EMPS FROM SELECT EMPLOYEE WHERE DNO = deptno; IF TOT_EMPS > 100 THEN RETURN “HUGE” ELSEIF TOT_EMPS > 50 THEN RETURN “LARGE” ELSEIF TOT_EMPS > 30 THEN RETURN “MEDIUM” ELSE RETURN “SMALL” ENDIF;

Example from SQL Server Books Online CREATE PROCEDURE INT OUTPUT AS – SELECT to return a result set summarizing -- employee sales. SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity) FROM Orders AS Ord JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID) GROUP BY Ord.EmployeeID ORDER BY Ord.EmployeeID -- SELECT to fill the output parameter with the -- maximum quantity from Order Details. = MAX(Quantity) FROM [Order Details] -- Return the number of all items ordered. RETURN (SELECT SUM(Quantity) FROM [Order Details])

Summary of Programming Techniques (Ch 9) A database may be accessed in an interactive mode Most often, however, data in a database is manipulate via application programs Several methods of database programming: Embedded SQL Dynamic SQL Stored Procedure and Function

SQL Triggers Database Programming can also be accomplished by incorporating Triggers Objective: to monitor a database and take initiate action when a condition occurs Triggers are expressed in a syntax that includes the following: Event Such as an insert, deleted, or update operation Condition Action To be taken when the condition is satisfied

Example: SQL Triggers A trigger to compare an employee’s salary to his/her supervisor during insert or update operations: CREATE TRIGGER INFORM_SUPERVISOR BEFORE INSERT OR UPDATE OF SALARY, SUPERVISOR_SSN ON EMPLOYEE FOR EACH ROW WHEN (NEW.SALARY> (SELECT SALARY FROM EMPLOYEE WHERE SSN=NEW.SUPERVISOR_SSN)) INFORM_SUPERVISOR (NEW.SUPERVISOR_SSN,NEW.SSN);