Lecture 15-16 SQL Prog Tecnhiques
Lecture 15-16 SQL Prog Tecnhiques
Chapter 9-2
Database Programming
• Objective: to access a database from an application
program (as opposed to interactive interfaces)
Chapter 9-3
Database Programming Approaches
Chapter 9-4
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
Chapter 9-5
Steps in Database Programming
Chapter 9-6
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 EXEC SQL and a
matching END-EXEC (or semicolon)
– shared variables (used in both languages) usually prefixed
with a colon (:) in SQL
Chapter 9-7
Example: Variable Declaration
in Language C
• Variables inside DECLARE are shared and can appear (while
prefixed by a colon) in SQL statements
• SQLCODE is used to communicate errors/exceptions between
the database and the program
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;
Chapter 9-8
SQL Commands for
Connecting to a Database
• Connection (multiple connections are possible but
only one is active)
CONNECT TO server-name AS connection-name
AUTHORIZATION user-account-info;
• Disconnection
DISCONNECT connection-name;
Chapter 9-9
Embedded SQL in C
Programming Examples
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);
END-EXEC
}
Chapter 9-10
Embedded SQL in C
Programming Examples
• A cursor (iterator) is needed to process multiple
tuples
Chapter 9-11
Example C program segment that uses cursors with embedded SQL for update purposes
0) prompt("Enter the Department Name: ", dname) ;
1) EXEC SQL
2) SELECT Dnumber INTO :dnumber
3) FROM DEPARTMENT WHERE Dname = :dname ;
4) EXEC SQL DECLARE EMP CURSOR FOR
5) SELECT Ssn, Fname, Minit, Lname, Salary
6) FROM EMPLOYEE WHERE Dno = :dnumber
7) FOR UPDATE OF Salary ;
8) EXEC SQL OPEN EMP ;
9) EXEC SQL FETCH FROM EMP INTO :ssn, :fname, :minit, :lname,
:salary ;
10) while (SQLCODE = = 0) {
11) printf("Employee name is:", Fname, Minit, Lname) ;
12) prompt("Enter the raise amount: ", raise) ;
13) EXEC SQL
14) UPDATE EMPLOYEE
15) SET Salary = Salary + :raise
16) WHERE CURRENT OF EMP ;
17) EXEC SQL FETCH FROM EMP INTO :ssn, :fname, :minit,
:lname, :salary ;
18) }
19) EXEC SQL CLOSE EMP ;
12
Dynamic SQL
• Objective: executing new (not previously compiled)
SQL statements at run-time
– a program accepts SQL statements from the keyboard at
run-time
– User Inputs a Query at Runtime, SQL Command is
prepared, command is executed
Chapter 9-13
Dynamic SQL: An Example
Chapter 9-14
Embedded SQL in Java
• SQLJ: a standard for embedding SQL in Java
• An SQLJ translator converts SQL statements into Java
(to be executed thru the JDBC interface)
• Certain classes, e.g., java.sql have to be
imported
Chapter 9-15
Importing classes needed for including SQLJ in Java programs in Oracle,
and establishing a connection and default context.
1) import java.sql.* ;
2) import java.io.* ; Note: SQLJ is primarily designed for
working with Oracle databases, and
3) import sqlj.runtime.* ;
support for MySQL using SQLJ is not
4) import sqlj.runtime.ref.* ; natively available. However, JDBC
5) import oracle.sqlj.runtime.* ; drivers can be used as a bridge
...
6) DefaultContext cntxt =
7) oracle.getConnection("<url name>", "<user name>",
"<password>", true) ;
17
Multiple Tuples in SQLJ
• SQLJ supports two types of iterators:
– named iterator: associated with a query result
– positional iterator: lists only attribute types in a query
result
• A FETCH operation retrieves the next tuple in a query
result:
fetch iterator-variable into program-variable
Chapter 9-18
Example: named iterator
0) dname = readEntry("Enter the Department Name: ") ;
1) try {
2) #sql { SELECT Dnumber INTO :dnumber
3) FROM DEPARTMENT WHERE Dname = :dname} ;
4) } catch (SQLException se) {
5) System.out.println("Department does not exist: " + dname);
6) Return ;
7) }
8) System.out.printline("Employee information for Department:
" + dname) ;
9) #sql iterator Emp(String ssn, String fname, String minit,
String lname, double salary) ;
10) Emp e = null ; Iterator object e of type Emp is created
11) #sql e = { SELECT ssn, fname, minit, lname, salary
12) FROM EMPLOYEE WHERE Dno = :dnumber} ;
13) while (e.next()) {
14) System.out.printline(e.ssn + " " + e.fname + " " +
e.minit + " " + e.lname + " " + e.salary) ;
15) } ;
16) e.close() ; 19
Example: positional iterator
0) dname = readEntry("Enter the Department Name: ") ;
1) try {
2) #sql { SELECT Dnumber INTO :dnumber
3) FROM DEPARTMENT WHERE Dname = :dname} ;
4) } catch (SQLException se) {
5) System.out.println("Department does not exist: " + dname) ;
6) Return ;
7) }
8) System.out.printline("Employee information for Department: " +
dname) ;
9) #sql iterator Emppos(String, String, String, String, double) ;
10) Emppos e = null ;
11) #sql e = { SELECT ssn, fname, minit, lname, salary
12) FROM EMPLOYEE WHERE Dno = :dnumber} ;
13) #sql { FETCH :e INTO :ssn, :fn, :mi, :ln, :sal} ;
14) while (!e.endFetch()) {
15) System.out.printline(ssn + " " + fn + " " + mi + " " + ln
+ " " + sal) ;
16) #sql { FETCH :e INTO :ssn, :fn, :mi, :ln, :sal} ;
17) } ;
20
18) e.close() ;
Database Programming with Functional Calls
Chapter 9-21
SQL Call Level Interface
• A part of the SQL standard
• Provides easy access to several databases within the
same program
• Certain libraries (e.g., sqlcli.h for C) have to be
installed and available
• SQL statements are dynamically created and passed
as string parameters in the calls
Chapter 9-22
Components of SQL/CLI
• Environment record: keeps track of database
connections
Chapter 9-23
//Reads a Social Security number of an employee and prints the employee’s last
name and salary
0) #include sqlcli.h ; Load SQL/CLI libraries (0)
1) void printDepartmentEmps() {
2) SQLHSTMT stmt1 ;
3) SQLHDBC con1 ; Declare record handle variables (2-5)
4) SQLHENV env1 ;
5) SQLRETURN ret1, ret2, ret3, ret4 ;
6) ret1 = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE,
&env1) ;
7) if (!ret1) ret2 = SQLAllocHandle(SQL_HANDLE_DBC, env1,
&con1) else exit ;
8) if (!ret2) ret3 = SQLConnect(con1, "dbs", SQL_NTS,
"js", SQL_NTS, "xyz",SQL_NTS) else exit ;
9) if (!ret3) ret4 = SQLAllocHandle(SQL_HANDLE_STMT, con1,
&stmt1) else exit ;
24
10) SQLPrepare(stmt1, "select Lname, Salary from EMPLOYEE
where Dno = ?", SQL_NTS) ;
Prepare a SQL statement (10)
Chapter 9-26
Example: Java program segment with JDBC
0) import java.io.* ;
1) import java.sql.* Import JDBC class libraries
...
2) class getEmpInfo {
3) public static void main (String args []) throws
SQLException, IOException { Load JDBC driver (4-7)
4) try { Class.forName("oracle.jdbc.driver.OracleDriver")
5) } catch (ClassNotFoundException x) {
6) System.out.println ("Driver could not be loaded") ;
7) }
8) String dbacct, passwrd, ssn, lname ; Create variables (8-9)
9) Double salary ;
10) dbacct = readentry("Enter database account:") ;
11) passwrd = readentry("Enter password:") ;
12) Connection conn = DriverManager.getConnection
13) ("jdbc:oracle:oci8:" + dbacct + "/" + passwrd) ;
28
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 connect object (via getConnection)
5. Create a statement object from the Statement
class:
1. PreparedStatment
2. CallableStatement
Chapter 9-29
Steps in JDBC Database Access
(continued)
6. Identify statement parameters (to be 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
Chapter 9-30
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
– enhance the modeling power of views
Chapter 9-31
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;
Chapter 9-32
SQL Persistent Stored Modules
Chapter 9-33
SQL/PSM: An Example
CREATE FUNCTION Dept_size (IN deptno INTEGER)
RETURNS VARCHAR[7]
DECLARE Tot_emps INTEGER;
Chapter 9-34
Summary
• A database may be accessed via an interactive
database
• 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
Chapter 9-35