Introduction to SQL Programming Techniques

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

Copyright © 2004 Pearson Education, Inc.. Chapter 9 More SQL: Assertions, Views, and Programming Techniques.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 9 Introduction to SQL Programming Techniques.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Objective: To access a database from an application program (as opposed to interactive interfaces) Why? An interactive interface is convenient but not.
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.
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.
Introduction to Structured Query Language (SQL)
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.
Advanced Database CS-426 Week 2 – Logic Query Languages, Object Model.
Dale Roberts 8/24/ Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
1 Section 6 Embedded SQL. 6-2 CA306 Embedded SQL Section Content 6.1Embedded SQL 6.2Java Database Connectivity 6.3Web Databases.
Overview of JDBC and Pro*C 1 Overview of JDBC,Pro*C and Oracle connectivity on Omega CSE 5330 – Database Systems.
Chapter 9 MORE SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 9- 1 DATADABASE PROGRAMMING 2Chapter 13 from our text.
CS 405G: Introduction to Database Systems Database programming.
Overview of JDBC and Pro*C 1 CSE 5330 – Database Systems.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Advanced SQL: Cursors & Stored Procedures
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.
Copyright  Oracle Corporation, All rights reserved. 7 Accessing a Database Using SQLJ.
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.
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.
1 CS 430 Database Theory Winter 2005 Lecture 14: Additional SQL Topics.
Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.
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.
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.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
Chapter 7 SQL HUANG XUEHUA. Chapter Objectives Specification of more general constraints via assertions SQL facilities for defining views (virtual.
Chapter 7 Chapter 7 Java Database Connectivity using JSP 1 (IS 203) WebProgramming (IS 203) Web Programming.
SQL- Updates, Assertions and Views. Data Definition, Constraints, and Schema Changes Used to CREATE, DROP, and ALTER the descriptions of the tables (relations)
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
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.
Structured Query Language (3) The main reference of this presentation is the textbook and PPT from : Elmasri & Navathe, Fundamental of Database Systems,
10/3/2017.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Chapter 4 An Introduction to SQL.
Lec - 14.
SQL Environment.
Web Technologies IT230 Dr Mohamed Habib.
Interacting with the Oracle Server
Views, Stored Procedures, Functions, and Triggers
Chapter 5: Advanced SQL Database System concepts,6th Ed.
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
Subject Name: DATABASE MANAGEMENT SYSTEM Subject Code: 10CS54
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Database System Concepts and Architecture.
CPSC-310 Database Systems
Introduction to Server-Side Web Development using JSP and Databases
Database Application Development
Interacting with Database
Advanced SQL: Views & Triggers
DB Programming: SQL Programming Techniques
Introduction to SQL Programming Techniques
Unit I-2.
Structured Query Language (3)
Chapter 8 Advanced SQL.
So What are Views and Triggers anyway?
SQL Views Presented by: Dr. Samir Tartir
Presentation transcript:

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

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.

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

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

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

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

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

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

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;

SQL Views: An Example

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;

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

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

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)

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

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 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

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

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

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

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

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");

JDBC usage steps - details Step 2 : Establish a connection try { con = DriverManager.getConnection("jdbc:oracle:thin:scott/tiger@orcl"); } catch(Exception e) System.out.println("Failed to connect to the database");

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 = 50000 WHERE FNAME = “John”; Statement.executeUpdate(query); (For UPDATE, INSERT, DELETE)

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

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

Online resources JDBC tutorial JDBC API reference http://java.sun.com/docs/books/tutorial/jdbc/ JDBC API reference http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.html

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

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=876543210; cout<<"The salary is :“<<a; } Be sure to include sqlca.h

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';

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;

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;

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

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; }

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.

Online reference Pro*C/C++ Precompiler Programmer's Guide http://omega.uta.edu/oracle/appdev.920/a97269/pc_01int.htm