Chapter 9 MORE  SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
Chapter Outline <ul><li>9.1  General Constraints as Assertions </li></ul><ul><li>9.2  Views in SQL </li></ul><ul><li>9.3  ...
Chapter Objectives <ul><li>Specification of more general constraints  via assertions </li></ul><ul><li>SQL facilities for ...
Constraints as Assertions <ul><li>General constraints: constraints that do not fit in the basic SQL categories (presented ...
Assertions: An Example <ul><li>“ The salary of an employee must not be greater than the salary of the manager of the depar...
Using General Assertions <ul><li>Specify a query that violates the condition; include inside a  NOT EXISTS  clause </li></...
SQL Triggers <ul><li>Objective: to monitor a database and take action when a condition occurs </li></ul><ul><li>Triggers a...
SQL Triggers: An Example <ul><li>A trigger to compare an employee’s salary to his/her supervisor during insert or update o...
Views in SQL <ul><li>A view is a “virtual” table that is derived from other tables </li></ul><ul><li>Allows for limited up...
Specification of Views <ul><li>SQL command:  CREATE VIEW </li></ul><ul><ul><li>a table (view) name </li></ul></ul><ul><ul>...
SQL Views: An Example <ul><li>Specify a different WORKS_ON table </li></ul><ul><li>CREATE VIEW WORKS_ON_NEW AS </li></ul><...
Using a Virtual Table <ul><li>We can specify SQL queries on a newly create table (view): </li></ul><ul><li>SELECT FNAME, L...
Efficient View Implementation (1) <ul><li>Query modification: present the view query in terms of a query on the underlying...
Efficient View Implementation (2) <ul><li>View materialization: involves physically creating and keeping a temporary table...
View Update <ul><li>Update on a single view without aggregate operations: update may map to an update on the underlying ba...
Un-updatable Views <ul><li>Views defined using groups and aggregate functions are not updateable </li></ul><ul><li>Views d...
Database Programming <ul><li>Objective: to access a database from an application program (as opposed to interactive interf...
Database Programming Approaches <ul><li>Embedded commands: database commands are embedded in a general-purpose programming...
Impedance Mismatch <ul><li>Incompatibilities between a host programming language and the database model, e.g., </li></ul><...
Steps in Database Programming <ul><li>Client program opens a connection to the database server </li></ul><ul><li>Client pr...
Embedded SQL <ul><li>Most SQL statements can be embedded in a general-purpose  host  programming language such as COBOL, C...
Example: Variable Declaration in Language C <ul><li>Variables inside  DECLARE  are shared and can appear  (while prefixed ...
SQL Commands for Connecting to a Database <ul><li>Connection (multiple connections are possible but only one is active) </...
Embedded SQL in C Programming Examples <ul><li>loop = 1; </li></ul><ul><li>while (loop) { </li></ul><ul><li>prompt (“Enter...
Embedded SQL in C Programming Examples <ul><li>A  cursor  (iterator) is needed to process multiple tuples </li></ul><ul><l...
Dynamic SQL <ul><li>Objective: executing new (not previously compiled) SQL statements at run-time </li></ul><ul><ul><li>a ...
Dynamic SQL: An Example <ul><li>EXEC SQL BEGIN DECLARE SECTION; </li></ul><ul><li>varchar sqlupdatestring[256]; </li></ul>...
Embedded SQL in Java <ul><li>SQLJ: a standard for embedding SQL in Java </li></ul><ul><li>An SQLJ translator converts SQL ...
Java Database Connectivity <ul><li>JDBC: SQL connection function calls for Java programming </li></ul><ul><li>A Java progr...
Steps in JDBC Database Access <ul><li>See Section 9.4.4. page 271-275 </li></ul><ul><li>Import JDBC library  (java.sql.*) ...
Steps in JDBC Database Access (continued) <ul><li>Identify statement parameters (to be designated by question marks) </li>...
Embedded SQL in Java: An Example (1/2) <ul><li>i mport java.sql.*; </li></ul><ul><li>i mport java.io.*; </li></ul><ul><li>...
Embedded SQL in Java: An Example (2/2) <ul><li>ssn = readEntry(“Enter a SSN: “); </li></ul><ul><li>try { </li></ul><ul><li...
Multiple Tuples in SQLJ <ul><li>SQLJ supports two types of iterators: </li></ul><ul><ul><li>named iterator : associated wi...
Database Programming with Functional Calls <ul><li>Embedded SQL provides static database programming </li></ul><ul><li>API...
SQL Call Level Interface <ul><li>A part of the SQL standard </li></ul><ul><li>Provides easy access to several databases wi...
Components of SQL/CLI <ul><li>Environment record : keeps track of database connections </li></ul><ul><li>Connection record...
Steps in C and SQL/CLI Programming <ul><li>Load SQL/CLI libraries  </li></ul><ul><li>Declare record handle variables for t...
Steps in C and SQL/CLI Programming (continued) <ul><li>Prepare a statement using SQL/CLI function  SQLPrepare </li></ul><u...
More Examples on SQL/CLI and JDBC <ul><li>See Section 9.5, page 275-283 </li></ul><ul><li>See Figure 9.11-9.14 </li></ul>
DB Programming in Perl (1) <ul><li>Install Perl:  http://www.activestate.com/ </li></ul><ul><li>I nstall modules of DBI, D...
DB Programming in Perl (2) <ul><li>sub Insert_into_DSN2_from_DSN1 { </li></ul><ul><li>my($dsn1, $dsn2) = @_;  my($DBH1, $s...
DB Programming in Perl (3) <ul><li># connect to the $dsn2 for writing </li></ul><ul><li>$DBH = DBI->connect( &quot;DBI:ODB...
DB Programming in Perl (4) <ul><li>P rint “Enter the department name:”; $dname = <STDIN>; </li></ul><ul><li>use DBI;  </li...
Database Stored Procedures <ul><li>Persistent procedures/functions (modules) are  stored locally and executed by the datab...
Stored Procedure Constructs <ul><li>A stored procedure </li></ul><ul><li>CREATE PROCEDURE procedure-name (params) </li></u...
SQL Persistent Stored Modules <ul><li>SQL/PSM: part of the SQL standard for writing persistent stored modules </li></ul><u...
SQL/PSM: An Example <ul><li>CREATE FUNCTION DEPT_SIZE (IN deptno INTEGER) </li></ul><ul><li>RETURNS VARCHAR[7] </li></ul><...
Summary <ul><li>Assertions provide a means to specify additional constraints </li></ul><ul><li>Triggers are a special kind...
Summary (continued) <ul><li>A database may be accessed via an interactive database </li></ul><ul><li>Most often, however, ...
Home Work <ul><li>Write a small Web-based DBMS application (such as the courses_students) that allows selecting a table an...
Upcoming SlideShare
Loading in …5
×

Chapter09

890 views
802 views

Published on

Fundmental of db by Ramez elmasry

Published in: Education, Technology
1 Comment
1 Like
Statistics
Notes
  • THIS IS VERY USEFUL
    so 'Thank You so Much'
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
890
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
43
Comments
1
Likes
1
Embeds 0
No embeds

No notes for slide

Chapter09

  1. 1. Chapter 9 MORE SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
  2. 2. Chapter Outline <ul><li>9.1 General Constraints as Assertions </li></ul><ul><li>9.2 Views in SQL </li></ul><ul><li>9.3 Database Programming </li></ul><ul><li>9.4 Embedded SQL </li></ul><ul><li>9.5 Functions Calls, SQL/CLI </li></ul><ul><li>9.6 Stored Procedures, SQL/PSM </li></ul><ul><li>9.7 Summary </li></ul>
  3. 3. Chapter Objectives <ul><li>Specification of more general constraints via assertions </li></ul><ul><li>SQL facilities for defining views (virtual tables) </li></ul><ul><li>Various techniques for accessing and manipulating a database via programs in general-purpose languages (e.g., Java) </li></ul>
  4. 4. Constraints as Assertions <ul><li>General constraints: constraints that do not fit in the basic SQL categories (presented in chapter 8) </li></ul><ul><li>Mechanism: CREAT ASSERTION </li></ul><ul><ul><li>components include: a constraint name, followed by CHECK , followed by a condition </li></ul></ul>
  5. 5. Assertions: An Example <ul><li>“ The salary of an employee must not be greater than the salary of the manager of the department that the employee works for’’ </li></ul><ul><li>CREATE ASSERTION SALARY_CONSTRAINT </li></ul><ul><li>CHECK (NOT EXISTS (SELECT * </li></ul><ul><li>FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D </li></ul><ul><li>WHERE E.SALARY > M.SALARY AND </li></ul><ul><li>E.DNO=D.NUMBER AND D.MGRSSN=M.SSN)) </li></ul>
  6. 6. Using General Assertions <ul><li>Specify a query that violates the condition; include inside a NOT EXISTS clause </li></ul><ul><li>Query result must be empty </li></ul><ul><ul><li>if the query result is not empty, the assertion has been violated </li></ul></ul>
  7. 7. SQL Triggers <ul><li>Objective: to monitor a database and take action when a condition occurs </li></ul><ul><li>Triggers are expressed in a syntax similar to assertions and include the following: </li></ul><ul><ul><li>event (e.g., an update operation) </li></ul></ul><ul><ul><li>condition </li></ul></ul><ul><ul><li>action (to be taken when the condition is satisfied) </li></ul></ul>
  8. 8. SQL Triggers: An Example <ul><li>A trigger to compare an employee’s salary to his/her supervisor during insert or update operations: </li></ul><ul><li>CREATE TRIGGER INFORM_SUPERVISOR </li></ul><ul><li>BEFORE INSERT OR UPDATE OF </li></ul><ul><li>SALARY, SUPERVISOR_SSN ON EMPLOYEE </li></ul><ul><li>FOR EACH ROW </li></ul><ul><li>WHEN </li></ul><ul><li>(NEW.SALARY> (SELECT SALARY FROM EMPLOYEE </li></ul><ul><li> WHERE SSN=NEW.SUPERVISOR_SSN)) </li></ul><ul><li>INFORM_SUPERVISOR (NEW.SUPERVISOR_SSN,NEW.SSN; </li></ul>
  9. 9. Views in SQL <ul><li>A view is a “virtual” table that is derived from other tables </li></ul><ul><li>Allows for limited update operations (since the table may not physically be stored) </li></ul><ul><li>Allows full query operations </li></ul><ul><li>A convenience for expressing certain operations </li></ul>
  10. 10. Specification of Views <ul><li>SQL command: CREATE VIEW </li></ul><ul><ul><li>a table (view) name </li></ul></ul><ul><ul><li>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) </li></ul></ul><ul><ul><li>a query to specify the table contents </li></ul></ul>
  11. 11. SQL Views: An Example <ul><li>Specify a different WORKS_ON table </li></ul><ul><li>CREATE VIEW WORKS_ON_NEW AS </li></ul><ul><li>SELECT FNAME, LNAME, PNAME, HOURS </li></ul><ul><li>FROM EMPLOYEE, PROJECT, WORKS_ON </li></ul><ul><li>WHERE SSN=ESSN AND PNO=PNUMBER </li></ul><ul><li>GROUP BY PNAME; </li></ul>
  12. 12. Using a Virtual Table <ul><li>We can specify SQL queries on a newly create table (view): </li></ul><ul><li>SELECT FNAME, LNAME FROM WORKS_ON_NEW </li></ul><ul><li>WHERE PNAME=‘Seena’; </li></ul><ul><li>When no longer needed, a view can be dropped: </li></ul><ul><li>DROP VIEW WORKS_ON_NEW; </li></ul>
  13. 13. Efficient View Implementation (1) <ul><li>Query modification: present the view query in terms of a query on the underlying base tables </li></ul><ul><ul><li>disadvantage: inefficient for views defined via complex queries (especially if additional queries are to be applied to the view within a short time period) </li></ul></ul>
  14. 14. Efficient View Implementation (2) <ul><li>View materialization: involves physically creating and keeping a temporary table </li></ul><ul><ul><li>assumption: other queries on the view will follow </li></ul></ul><ul><ul><li>concerns: maintaining correspondence between the base table and the view when the base table is updated </li></ul></ul><ul><ul><li>strategy: incremental update </li></ul></ul>
  15. 15. View Update <ul><li>Update on a single view without aggregate operations: update may map to an update on the underlying base table </li></ul><ul><li>Views involving joins: an update may map to an update on the underlying base relations </li></ul><ul><ul><li>not always possible </li></ul></ul>
  16. 16. Un-updatable Views <ul><li>Views defined using groups and aggregate functions are not updateable </li></ul><ul><li>Views defined on multiple tables using joins are generally not updateable </li></ul><ul><li>WITH CHECK OPTION : must be added to the definition of a view if the view is to be updated </li></ul><ul><ul><li>to allow check for updatability and to plan for an execution strategy </li></ul></ul>
  17. 17. Database Programming <ul><li>Objective: to access a database from an application program (as opposed to interactive interfaces) </li></ul><ul><li>Why? An interactive interface is convenient but not sufficient; a majority of database operations are made thru application programs (nowadays thru web applications) </li></ul>
  18. 18. Database Programming Approaches <ul><li>Embedded commands: database commands are embedded in a general-purpose programming language </li></ul><ul><li>Library of database functions: available to the host language for database calls; known as an API </li></ul><ul><li>A brand new, full-fledged language (minimizes impedance mismatch) </li></ul>
  19. 19. Impedance Mismatch <ul><li>Incompatibilities between a host programming language and the database model, e.g., </li></ul><ul><ul><li>type mismatch and incompatibilities; requires a new binding for each language </li></ul></ul><ul><ul><li>set vs. record-at-a-time processing </li></ul></ul><ul><ul><ul><li>need special iterators to loop over query results and manipulate individual values </li></ul></ul></ul>
  20. 20. Steps in Database Programming <ul><li>Client program opens a connection to the database server </li></ul><ul><li>Client program submits queries to and/or updates the database </li></ul><ul><li>When database access is no longer needed, client program terminates the connection </li></ul>
  21. 21. Embedded SQL <ul><li>Most SQL statements can be embedded in a general-purpose host programming language such as COBOL, C, Java </li></ul><ul><li>An embedded SQL statement is distinguished from the host language statements by EXEC SQL and a matching END-EXEC (or semicolon) </li></ul><ul><ul><li>shared variables (used in both languages) usually prefixed with a colon (:) in SQL </li></ul></ul>
  22. 22. Example: Variable Declaration in Language C <ul><li>Variables inside DECLARE are shared and can appear (while prefixed by a colon) in SQL statements </li></ul><ul><li>SQLCODE is used to communicate errors/exceptions between the database and the program </li></ul><ul><li>int loop; </li></ul><ul><li>EXEC SQL BEGIN DECLARE SECTION; </li></ul><ul><li>varchar dname[16], fname[16], …; </li></ul><ul><li>char ssn[10], bdate[11], …; </li></ul><ul><li>int dno, dnumber, SQLCODE, …; </li></ul><ul><li>EXEC SQL END DECLARE SECTION; </li></ul>
  23. 23. SQL Commands for Connecting to a Database <ul><li>Connection (multiple connections are possible but only one is active) </li></ul><ul><li>CONNECT TO server-name AS connection-name </li></ul><ul><li>AUTHORIZATION user-account-info; </li></ul><ul><li>Change from an active connection to another one </li></ul><ul><li>SET CONNECTION connection-name; </li></ul><ul><li>Disconnection </li></ul><ul><li>DISCONNECT connection-name; </li></ul>
  24. 24. Embedded SQL in C Programming Examples <ul><li>loop = 1; </li></ul><ul><li>while (loop) { </li></ul><ul><li>prompt (“Enter SSN: “, ssn); </li></ul><ul><li>EXEC SQL </li></ul><ul><li>select FNAME, LNAME, ADDRESS, SALARY </li></ul><ul><li>into :fname, :lname, :address, :salary </li></ul><ul><li>from EMPLOYEE where SSN == :ssn; </li></ul><ul><li>if (SQLCODE == 0) printf(fname, …); </li></ul><ul><li>else printf(“SSN does not exist: “, ssn); </li></ul><ul><li>prompt(“More SSN? (1=yes, 0=no): “, loop); </li></ul><ul><li>END-EXEC </li></ul><ul><li>} </li></ul>
  25. 25. Embedded SQL in C Programming Examples <ul><li>A cursor (iterator) is needed to process multiple tuples </li></ul><ul><li>FETCH commands move the cursor to the next tuple </li></ul><ul><li>CLOSE CURSOR indicates that the processing of query results has been completed </li></ul><ul><li>See Fig. 9.4 </li></ul>
  26. 26. Dynamic SQL <ul><li>Objective: executing new (not previously compiled) SQL statements at run-time </li></ul><ul><ul><li>a program accepts SQL statements from the keyboard at run-time </li></ul></ul><ul><ul><li>a point-and-click operation translates to certain SQL query </li></ul></ul><ul><li>Dynamic update is relatively simple; dynamic query can be complex </li></ul><ul><ul><li>because the type and number of retrieved attributes are unknown at compile time </li></ul></ul>
  27. 27. Dynamic SQL: An Example <ul><li>EXEC SQL BEGIN DECLARE SECTION; </li></ul><ul><li>varchar sqlupdatestring[256]; </li></ul><ul><li>EXEC SQL END DECLARE SECTION; </li></ul><ul><li>… </li></ul><ul><li>prompt (“Enter update command:“, sqlupdatestring); </li></ul><ul><li>EXEC SQL PREPARE sqlcommand FROM :sqlupdatestring; </li></ul><ul><li>EXEC SQL EXECUTE sqlcommand; </li></ul>
  28. 28. Embedded SQL in Java <ul><li>SQLJ: a standard for embedding SQL in Java </li></ul><ul><li>An SQLJ translator converts SQL statements into Java (to be executed thru the JDBC interface) </li></ul><ul><li>Certain classes, e.g., java.sql have to be imported </li></ul>
  29. 29. Java Database Connectivity <ul><li>JDBC: SQL connection function calls for Java programming </li></ul><ul><li>A Java program with JDBC functions can access any relational DBMS that has a JDBC driver </li></ul><ul><li>JDBC allows a program to connect to several databases (known as data sources ) </li></ul>
  30. 30. Steps in JDBC Database Access <ul><li>See Section 9.4.4. page 271-275 </li></ul><ul><li>Import JDBC library (java.sql.*) </li></ul><ul><li>Load JDBC driver: Class.forname(“oracle.jdbc.driver.OracleDriver”) </li></ul><ul><li>Define appropriate variables </li></ul><ul><li>Create a connect object (via getConnection ) </li></ul><ul><li>Create a statement object from the Statement class: </li></ul><ul><ul><li>PreparedStatment </li></ul></ul><ul><ul><li>CallableStatement </li></ul></ul>
  31. 31. Steps in JDBC Database Access (continued) <ul><li>Identify statement parameters (to be designated by question marks) </li></ul><ul><li>Bound parameters to program variables </li></ul><ul><li>Execute SQL statement (referenced by an object) via JDBC’s executeQuery </li></ul><ul><li>Process query results (returned in an object of type ResultSet ) </li></ul><ul><ul><li>ResultSet is a 2-dimentional table </li></ul></ul>
  32. 32. Embedded SQL in Java: An Example (1/2) <ul><li>i mport java.sql.*; </li></ul><ul><li>i mport java.io.*; </li></ul><ul><li>i mport sqlj.runtime.*; </li></ul><ul><li>i mport sqlj.runtime.ref.*; </li></ul><ul><li>i mport oracle.sqlj.runtime.*; </li></ul><ul><li>… </li></ul><ul><li>DefaultContext cntxt = oracle.getConnection(“<url name>”, “<user name>”, “<password>”, true); </li></ul><ul><li>DefaultContext.setDefaultContext(cntxt); </li></ul><ul><li>… </li></ul><ul><li>string dname, ssn, fname, fn, lname, ln, bdate, address; </li></ul><ul><li>char sex, minit, mi; </li></ul><ul><li>double salary, sal; </li></ul><ul><li>integer dno, dnumber; </li></ul>
  33. 33. Embedded SQL in Java: An Example (2/2) <ul><li>ssn = readEntry(“Enter a SSN: “); </li></ul><ul><li>try { </li></ul><ul><li>#sql{select FNAME, LNAME, ADDRESS, SALARY </li></ul><ul><li>into :fname, :lname, :address, :salary </li></ul><ul><li>from EMPLOYEE where SSN = :ssn}; </li></ul><ul><li>} </li></ul><ul><li>catch (SQLException se) { </li></ul><ul><li>System.out.println(“SSN does not exist: “,+ssn); </li></ul><ul><li>return; </li></ul><ul><li>} </li></ul><ul><li>System.out.println(fname+“ “+lname+… ); </li></ul>
  34. 34. Multiple Tuples in SQLJ <ul><li>SQLJ supports two types of iterators: </li></ul><ul><ul><li>named iterator : associated with a query result </li></ul></ul><ul><ul><li>positional iterator : lists only attribute types in a query result </li></ul></ul><ul><li>A FETCH operation retrieves the next tuple in a query result: </li></ul><ul><li>fetch iterator-variable into program-variable </li></ul><ul><li>See Fig. 9.9 and 9.10, compare them with Fig. 9.4 </li></ul>
  35. 35. Database Programming with Functional Calls <ul><li>Embedded SQL provides static database programming </li></ul><ul><li>API: dynamic database programming with a library of functions </li></ul><ul><ul><li>advantage: no preprocessor needed (thus more flexible) </li></ul></ul><ul><ul><li>drawback: SQL syntax checks to be done at run-time </li></ul></ul>
  36. 36. SQL Call Level Interface <ul><li>A part of the SQL standard </li></ul><ul><li>Provides easy access to several databases within the same program </li></ul><ul><li>Certain libraries (e.g., sqlcli.h for C) have to be installed and available </li></ul><ul><li>SQL statements are dynamically created and passed as string parameters in the calls </li></ul>
  37. 37. Components of SQL/CLI <ul><li>Environment record : keeps track of database connections </li></ul><ul><li>Connection record : keep tracks of info needed for a particular connection </li></ul><ul><li>Statement record : keeps track of info needed for one SQL statement </li></ul><ul><li>Description record : keeps track of tuples </li></ul>
  38. 38. Steps in C and SQL/CLI Programming <ul><li>Load SQL/CLI libraries </li></ul><ul><li>Declare record handle variables for the above components (called: SQLHSTMT, SQLHDBC, SQLHENV, SQLHDEC ) </li></ul><ul><li>Set up an environment record using SQLAllocHandle </li></ul><ul><li>Set up a connection record using SQLAllocHandle </li></ul><ul><li>Set up a statement record using SQLAllocHandle </li></ul>
  39. 39. Steps in C and SQL/CLI Programming (continued) <ul><li>Prepare a statement using SQL/CLI function SQLPrepare </li></ul><ul><li>Bound parameters to program variables </li></ul><ul><li>Execute SQL statement via SQLExecute </li></ul><ul><li>Bound columns in a query to a C variable via SQLBindCol </li></ul><ul><li>Use SQLFetch to retrieve column values into C variables </li></ul>
  40. 40. More Examples on SQL/CLI and JDBC <ul><li>See Section 9.5, page 275-283 </li></ul><ul><li>See Figure 9.11-9.14 </li></ul>
  41. 41. DB Programming in Perl (1) <ul><li>Install Perl: http://www.activestate.com/ </li></ul><ul><li>I nstall modules of DBI, DBD:ODBC: </li></ul><ul><ul><li>ppm install DBI </li></ul></ul><ul><ul><li>ppm install DBD-ODBC </li></ul></ul><ul><li>Set DSN (Data Source Name) </li></ul><ul><ul><li>控制台 => 系統管理工具 => 資料來源 (ODBC)=> 系統資料來源名稱 </li></ul></ul><ul><ul><li>E.g., set a DSN=NSC_PatentDB for the file NSC_PatentDB.mdb. </li></ul></ul>
  42. 42. DB Programming in Perl (2) <ul><li>sub Insert_into_DSN2_from_DSN1 { </li></ul><ul><li>my($dsn1, $dsn2) = @_; my($DBH1, $sql1, $STH1, $DBH, $sql, $STH); </li></ul><ul><li>use DBI; # connect to the $dsn1 for reading </li></ul><ul><li>$DBH1 = DBI->connect( &quot;DBI:ODBC:$dsn1&quot;,,, { </li></ul><ul><li>RaiseError => 1, AutoCommit => 0 </li></ul><ul><li>}) or die &quot;Can't connect database : $DBI::errstrn&quot;; </li></ul><ul><li>$DBH1->{LongReadLen}=1280000; # only work for SELECT, not for INSERT </li></ul><ul><li>$DBH1->{LongTruncOk} = 1; </li></ul><ul><li>$sql1 = &quot;SELECT TDescription.PatentNo, TypeNo, Title, Abstract FROM TDescription, TPatentInfo where TDescription.PatentNo = TPatentInfo.PatentNo </li></ul><ul><li>order by TDescription.PatentNo, TypeNo&quot;; </li></ul><ul><li>$STH1 = $DBH1->prepare($sql1) </li></ul><ul><li>or die &quot;Can't prepare SQL statement: SQL=$sql, $DBI::errstrn&quot;; </li></ul><ul><li>$STH1->execute() </li></ul><ul><li>or die &quot;Can't run SQL statement: SQL=$sql, $STH::errstrn&quot;; </li></ul>
  43. 43. DB Programming in Perl (3) <ul><li># connect to the $dsn2 for writing </li></ul><ul><li>$DBH = DBI->connect( &quot;DBI:ODBC:$dsn2&quot;,,, { RaiseError => 1, AutoCommit => 0 }) or die &quot;Can't connect database : $DBI::errstrn&quot;; </li></ul><ul><li>$sql = qq{ INSERT INTO Seg_Abs6 (Sno, DName, [Desc]) values (?, ?, ?) }; </li></ul><ul><li>$STH = $DBH->prepare($sql) </li></ul><ul><li>or die &quot;Can't prepare SQL statement: SQL=$sql, $DBI::errstrn&quot;; </li></ul><ul><li>$STH->bind_param(3, $STH, DBI::SQL_LONGVARCHAR); </li></ul><ul><li>while (($pid, $TypeNo, $Title, $Abs) = $STH1->fetchrow_array) { </li></ul><ul><li> next if $TypeNo > 5; </li></ul><ul><li>$Abs =~ s/<BR><BR>/n/g; $Abstract .= $Abs . &quot;nn&quot;; </li></ul><ul><li> if ($TypeNo == 5) { </li></ul><ul><li> $STH->execute($pid, $Title, $Abstract) </li></ul><ul><li>or die &quot;Can't run SQL statement: SQL=$sql, $STH::errstrn&quot;; </li></ul><ul><li> $Abstract = &quot;&quot;; </li></ul><ul><li> } </li></ul><ul><li>} </li></ul><ul><li>$STH1->finish; $DBH1->disconnect; $STH->finish; $DBH->disconnect; </li></ul><ul><li>} </li></ul>
  44. 44. DB Programming in Perl (4) <ul><li>P rint “Enter the department name:”; $dname = <STDIN>; </li></ul><ul><li>use DBI; </li></ul><ul><li>$DBH = DBI->connect( &quot;DBI:ODBC:$dsn1&quot;,,, { </li></ul><ul><li>RaiseError => 1, AutoCommit => 0 </li></ul><ul><li>}) or die &quot;Can't connect database : $DBI::errstrn&quot;; </li></ul><ul><li>$sql = &quot;SELECT dnumber FROM department WHERE dname = ?&quot;; </li></ul><ul><li>$STH = $DBH->prepare($sql) or die &quot;SQL=$sql, $DBI::errstrn&quot;; </li></ul><ul><li>$STH->execute($dname) or die &quot;SQL=$sql, $STH::errstrn&quot;; </li></ul><ul><li>($dno) = $STH->fetchrow_array; </li></ul><ul><li>print “Employee information for Department: $dname”; </li></ul><ul><li>$sql = &quot;SELECT ssn,lname, salary FROM employee WHERE dno = ?&quot;; </li></ul><ul><li>$STH = $DBH->prepare($sql) or die &quot;SQL=$sql, $DBI::errstrn&quot;; </li></ul><ul><li>$STH->execute($dno) or die &quot;SQL=$sql, $STH::errstrn&quot;; </li></ul><ul><li>while (($ssn, $lname, $salary) = $STH->fetchrow_array) { </li></ul><ul><li>print “ssn=$ssn, LastName=$lname, Salary=$salaryn”; </li></ul><ul><li>} </li></ul><ul><li>$STH->finish; $DBH->disconnect; </li></ul>
  45. 45. Database Stored Procedures <ul><li>Persistent procedures/functions (modules) are stored locally and executed by the database server (as opposed to execution by clients) </li></ul><ul><li>Advantages: </li></ul><ul><ul><li>if the procedure is needed by many applications, it can be invoked by any of them (thus reduce duplications) </li></ul></ul><ul><ul><li>execution by the server reduces communication costs </li></ul></ul><ul><ul><li>enhance the modeling power of views </li></ul></ul>
  46. 46. Stored Procedure Constructs <ul><li>A stored procedure </li></ul><ul><li>CREATE PROCEDURE procedure-name (params) </li></ul><ul><li>local-declarations </li></ul><ul><li>procedure-body; </li></ul><ul><li>A stored function </li></ul><ul><li>CREATE FUNCTION fun-name (params) RETRUNS return-type </li></ul><ul><li>local-declarations </li></ul><ul><li>function-body; </li></ul><ul><li>Calling a procedure or function </li></ul><ul><li>CALL procedure-name/fun-name (arguments); </li></ul>
  47. 47. SQL Persistent Stored Modules <ul><li>SQL/PSM: part of the SQL standard for writing persistent stored modules </li></ul><ul><li>SQL + stored procedures/functions + additional programming constructs </li></ul><ul><ul><li>e.g., branching and looping statements </li></ul></ul><ul><ul><li>enhance the power of SQL </li></ul></ul>
  48. 48. SQL/PSM: An Example <ul><li>CREATE FUNCTION DEPT_SIZE (IN deptno INTEGER) </li></ul><ul><li>RETURNS VARCHAR[7] </li></ul><ul><li>DECLARE TOT_EMPS INTEGER; </li></ul><ul><li>SELECT COUNT (*) INTO TOT_EMPS </li></ul><ul><li>FROM SELECT EMPLOYEE WHERE DNO = deptno; </li></ul><ul><li>IF TOT_EMPS > 100 THEN RETURN “HUGE” </li></ul><ul><li>ELSEIF TOT_EMPS > 50 THEN RETURN “LARGE” </li></ul><ul><li>ELSEIF TOT_EMPS > 30 THEN RETURN “MEDIUM” </li></ul><ul><li>ELSE RETURN “SMALL” </li></ul><ul><li>ENDIF; </li></ul>
  49. 49. Summary <ul><li>Assertions provide a means to specify additional constraints </li></ul><ul><li>Triggers are a special kind of assertions; they define actions to be taken when certain conditions occur </li></ul><ul><li>Views are a convenient means for creating temporary (virtual) tables </li></ul>
  50. 50. Summary (continued) <ul><li>A database may be accessed via an interactive database </li></ul><ul><li>Most often, however, data in a database is manipulate via application programs </li></ul><ul><li>Several methods of database programming: </li></ul><ul><ul><li>embedded SQL </li></ul></ul><ul><ul><li>dynamic SQL </li></ul></ul><ul><ul><li>stored procedure and function </li></ul></ul>
  51. 51. Home Work <ul><li>Write a small Web-based DBMS application (such as the courses_students) that allows selecting a table and then </li></ul><ul><ul><li>Inserting a record </li></ul></ul><ul><ul><li>Updating a record </li></ul></ul><ul><ul><li>Deleting a record </li></ul></ul><ul><ul><li>Selecting records based on some constraints </li></ul></ul><ul><li>Using PHP, Perl, and Java, respectively. </li></ul>

×