Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to SQL Programming Techniques

Similar presentations


Presentation on theme: "Introduction to SQL Programming Techniques"— Presentation transcript:

1

2 Introduction to SQL Programming Techniques
Chapter 9 Introduction to SQL Programming Techniques Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe

3 Chapter Objectives Specification of more general constraints via assertions SQL facilities for defining views (virtual tables) Various techniques for accessing and manipulating a database via programs in general-purpose languages E.g., Java, C++, etc.

4 Constraints as Assertions
General constraints: constraints that do not fit in the basic SQL categories (presented in chapter 8) Mechanism: CREAT ASSERTION Components include: a constraint name, followed by CHECK, followed by a condition

5 Assertions: An Example
“The salary of an employee must not be greater than the salary of the manager of the department that the employee works for’’ CREAT ASSERTION SALARY_CONSTRAINT CHECK (NOT EXISTS (SELECT * FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D WHERE E.SALARY > M.SALARY AND E.DNO=D.NUMBER AND D.MGRSSN=M.SSN)) constraint name, CHECK, condition

6 Using General Assertions
Specify a query that violates the condition; include inside a NOT EXISTS clause Query result must be empty if the query result is not empty, the assertion has been violated

7 SQL Triggers Objective: to monitor a database and take initiate action when a condition occurs A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database. Triggers are expressed in a syntax similar to assertions and include the following: Event Such as an insert, deleted, or update operation Condition Action To be taken when the condition is satisfied

8 Views in SQL A view is a “virtual” table that is derived from other tables Allows for limited update operations Since the table does not physically be stored Allows full query operations

9 Specification of Views
SQL command: CREATE VIEW a table (view) name a possible list of attribute names (for example, when arithmetic operations are specified or when we want the names to be different from the attributes in the base relations) a query to specify the view contents

10 SQL Views: An Example Specify a different WORKS_ON table
CREATE VIEW WORKS_ON_NEW AS SELECT FNAME, LNAME, PNAME, HOURS FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBER GROUP BY PNAME;

11 SQL Views: An Example

12 Using a Virtual Table We can specify SQL queries on a newly create table (view): SELECT FNAME, LNAME FROM WORKS_ON_NEW WHERE PNAME=‘Seena’; View is always up-to-date Responsibility of the DBMS and not the user When no longer needed, a view can be dropped: DROP WORKS_ON_NEW;

13 Updatable Views Update on a view defined on a single table without any aggregate functions: Update may map to an update on the underlying base table Views involving joins: Often not possible for DBMS to determine which of the updates is intended

14 Un-updatable Views Views defined using groups and aggregate functions are not updateable Views defined on multiple tables using joins are generally not updateable WITH CHECK OPTION: must be added at the end of the view definition if a view is to be updated

15 Database Programming Objective: Why?
To access a database from an application program Why? An interactive interface is convenient but not sufficient A majority of database operations are made thru application programs (increasingly thru web applications)

16 Database Programming Approaches
Embedded commands: Database commands are embedded in a general-purpose programming languag Library of database functions: Available to the host language for database calls; known as an API API standards for Application Program Interface

17 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

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

19 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

20 Java Database Connectivity (JDBC)
JDBC provides a standardized library for accessing relational databases Connecting to the database Initiating queries Creating stored (parameterized) queries Data structure for the query result JDBC is not embedded SQL JDBC driver for Oracle needs to be on the client machine JDBC is located in java.sql package

21 JDBC driver Java application JDBC driver manager Oracle JDBC driver
JDBC API JDBC driver manager JDBC driver API Oracle JDBC driver Client Oracle database Server

22 Six steps in using JDBC Load the driver Establish a connection
Create a statement object Execute a query Process the results Close the connection

23 JDBC usage steps - details
Step 1 : Load the driver try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch(Exception e) System.out.println("JDBC ORACLE driver failed to load");

24 JDBC usage steps - details
Step 2 : Establish a connection try { con = } catch(Exception e) System.out.println("Failed to connect to the database");

25 JDBC usage steps - details
Step 3 : Create a statement Statement statement = con.createStatement(); Step 4 : Execute a query String query = “SELECT FNAME, SALARY FROM EMPLOYEE”; ResultSet rs = Statement.executeQuery(query); (For SELECT) String query = “UPDATE EMPLOYEE SET SALARY = WHERE FNAME = “John”; Statement.executeUpdate(query); (For UPDATE, INSERT, DELETE)

26 JDBC usage steps - details
Step 5 : Process the result While (rs.next()) { System.out.println(rs.getString(1) + “ “ + rs.getInt(2)); } First column has index 1, not 0 ResultSet provides various getXXX methods that take a column index, and return the data

27 JDBC usage steps - details
Step 6 : Close the connection con.close(); As opening a connection is expensive, postpone this step if additional database operations are expected

28 Online resources JDBC tutorial JDBC API reference
JDBC API reference

29 Pro*C Pro*C program C code Executable SQLLIB Embedded SQL
Allows you to embed SQL in C code Pre-compiler C compiler Pro*C program C code Executable Embedded SQL statements SQL statements replaced By library calls SQLLIB Oracle runtime library

30 Pro*C++ syntax SQL statements can be placed anywhere between a C++ block All SQL statements need to start with EXEC SQL and be terminated by a semicolon { int a; /* ... */ EXEC SQL SELECT salary INTO :a FROM Employee WHERE SSN= ; cout<<"The salary is :“<<a; } Be sure to include sqlca.h

31 Connecting to the database
Legal way char *username = "SCOTT"; char *password = "TIGER"; EXEC SQL CONNECT :username IDENTIFIED BY :password; Illegal way EXEC SQL CONNECT SCOTT IDENTIFIED BY TIGER; EXEC SQL CONNECT 'SCOTT' IDENTIFIED BY 'TIGER';

32 Dynamic sql Used to dynamically create entire SQL statements
char *s = "INSERT INTO emp VALUES(1234, 'jon', 3)"; EXEC SQL PREPARE q FROM :s; EXEC SQL EXECUTE q; Alternately, EXEC SQL EXECUTE IMMEDIATE :s;

33 Host variables Key to the communication between the host program and the database They should be declared in a Declare section EXEC SQL BEGIN DECLARE SECTION; /* Declare all host variables inside this section: */ char *uid = "scott/tiger"; ... EXEC SQL END DECLARE SECTION;

34 Transactions Sequence of SQL statements that are treated as a single unit of work Transaction ends when you issue EXEC SQL COMMIT;

35 Cursors Used for fetching multiple rows of data First, declare it.
EXEC SQL DECLARE emp_cursor CURSOR FOR SELECT ename, empno, sal FROM emp WHERE deptno = :dept_number; Then, open it. EXEC SQL OPEN emp_cursor; Fetch the records (move the cursor to the next tuple). for (;;) { EXEC SQL FETCH emp_cursor INTO :emp_name1, :emp_no1, :salary1; }

36 Cursors (continued) Finally, close it. EXEC SQL CLOSE emp_cursor;
Error handling Every executable SQL statement returns a status code to the SQLCA variable sqlcode A zero status code means that Oracle executed the statement without detecting an error or exception A positive status code means that Oracle executed the statement but detected an exception A negative status code means that Oracle did not execute the SQL statement because of an error.

37 Online reference Pro*C/C++ Precompiler Programmer's Guide


Download ppt "Introduction to SQL Programming Techniques"

Similar presentations


Ads by Google