SlideShare une entreprise Scribd logo
1  sur  60
Database Programming
Techniques
CMPS 277
Raji Ghawi
rg31@aub.edu.lb
7 April 2015
Interaction with Databases
• Interactive interface
– SQL commands typed directly into a monitor
– Execute file of commands
• @<filename>
• Application programs or database applications
– Used as canned transactions by the end users access a
database
– May have Web interface
– Host language: Java, C/C++/C# , …
– Database language: SQL
Database Programming Approaches
• Embedded SQL Approach
– Embedded SQL ( C language)
– SQLJ (Java language)
• Library of Function Calls Approach.
– JDBC
– SQL/CLI
• Database Programming Language Approach
– Stored Procedures
Database Programming Approaches
• Embedded SQL Approach
– Embedded SQL ( C language)
– SQLJ (Java language)
• Library of Function Calls Approach.
– JDBC
– SQL/CLI
• Database Programming Language Approach
– Stored Procedures
JDBC
One API to Access Them All
Introduction
• JDBC: Java DataBase Connectivity
• JDBC is a standard interface that lets you access
virtually any tabular data source from the Java
programming language
– relational databases, spreadsheets, flat files
• The JDBC classes and interfaces are in the java.sql
package
General Architecture
Java Application or Applet
JDBC Driver Manager
Oracle
Driver
MySQL
Driver
PostgreSQL
Driver
Oracle PostgreSQLMySQL
• The Driver Manager
provides a consistent
layer between your
Java application and
back-end database.
• Is an interpreter that translates JDBC method calls to vendor-
specific database commands
• Implements interfaces in java.sql
• Can also provide a vendor’s extensions to the JDBC standard
Driver
JDBC calls
Database
commands
Database
A JDBC Driver
Query
Close
Connect
Process results
Overview of Querying a Database With JDBC
Register the driver
Connect to the database
Stage 1: Connect
Query
Close
Connect
Process results
1. Register the driver.
2. Connect to the database.
DriverManager.registerDriver(new org.postgresql.Driver());
Connection conn = DriverManager.getConnection
(URL, userid, password);
Connection conn = DriverManager.getConnection
("jdbc:postgresql://localhost/University",
"xxxx", "xxxx");
How to Make the Connection
Using Connection
java.sql.Connection Creating Statement
Transaction Management
Get database metadata
Conneciton related
createStatment()
prepareStatment(String)
prepareCall(String)
commit()
rollback()
getMetaData()
close()
isClosed()
List of JDBC Drivers
DBMS Driver / URL
PostgreSQL
org.postgresql.Driver
jdbc:postgresql://[host]/[DB]
MySQL
com.mysql.jdbc.Driver
jdbc:mysql://[host]/[DB]
Oracle
oracle.jdbc.driver.OracleDriver
jdbc:oracle:thin:@[host]:[port]:[db]
jdbc:oracle:oci:@[host]:[port]:[db]
SQL Server
com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc:sqlserver://[host];databaseName=[db];
ODBC bridge
sun.jdbc.odbc.JdbcOdbcDriver
jdbc:odbc:[db]
Demonstration
import java.sql.*;
public class MyDBApp1 {
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost/University";
String username = "xxxx";
String passwd = "xxxx";
try {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection(url, username, passwd);
// do something with connection
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Create a statement
Query the database
Stage 2: Query
Query
Close
Connect
Process results
The Statement Object
• A Statement object sends your SQL statement
to the database.
• You need an active connection to create a
JDBC statement.
• Statement has three methods to execute a
SQL statement:
– executeQuery() for SELECT statements
– executeUpdate() for INSERT, UPDATE, DELETE, or
DDL statements
– execute() for either type of statement
1. Create an empty statement object.
2. Execute the statement.
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(statement);
int count = stmt.executeUpdate(statement);
boolean isquery = stmt.execute(statement);
How to Query the Database
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery
("SELECT fname, lname FROM student");
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("DELETE FROM student WHERE studid = '201231521'");
Querying the Database: Examples
• Execute a select statement.
• Execute a delete statement.
Step through the results
Assign results to Java variables
Stage 3: Process the Results
Close
Connect
Process results
Query
The ResultSet Object
• JDBC returns the results of a query in a
ResultSet object.
• A ResultSet maintains a cursor pointing to its
current row of data.
• Use next() to step through the result set row
by row.
• getString(), getInt(), and so on assign each
value to a Java variable.
1. Step through the result set.
2. Use getXXX() to get each column value.
while (rset.next()) { … }
String val =
rset.getString(colname);
while (rset.next()) {
String fname = rset.getString("fname");
String email = rset.getString("email");
// Process or display the data
}
String val =
rset.getString(colIndex);
How to Process the Results
while (rset.next()) {
String email = rset.getString("email");
if (rset.wasNull() {
… // Handle null value
}
…}
How to Handle SQL Null Values
• Java primitive types cannot have null values.
• Do not use a primitive type when your query
might return a SQL null.
• Use ResultSet.wasNull() to determine whether
a column has a null value.
Mapping Database Types to Java
Types
• ResultSet maps database types to Java types.
ResultSet rset = stmt.executeQuery
("SELECT id, birth_date, name FROM student");
int id = rset.getInt(1);
Date birthdate = rset.getDate(2);
String name = rset.getString(3);
Column Name Type
id INTEGER
birthdate DATE
name VARCHAR
JDBC Type Java Type
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT
DOUBLE
double
BINARY
VARBINARY
LONGVARBINARY
byte[]
CHAR
VARCHAR
LONGVARCHAR
String
Mapping Database Types to Java
Types
JDBC Type Java Type
NUMERIC
DECIMAL
BigDecimal
DATE java.sql.Date
TIME
TIMESTAMP
java.sql.Timestamp
CLOB Clob*
BLOB Blob*
ARRAY Array*
STRUCT Struct*
REF Ref*
JAVA_OBJECT underlying Java class
* SQL3 data type supported in JDBC 2.0
Close the result set
Close the statement
Close the connection
Stage 4: Close
Close
Connect
Query
Process Results
1. Close the ResultSet object.
2. Close the Statement object.
3. Close the connection.
rset.close();
stmt.close();
conn.close();
How to Close the Connection
Demonstration
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost/University";
String username = "xxxx";
String passwd = "xxxx";
try {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection(url, username, passwd);
Statement stmt = connection.createStatement();
String sql2 = "SELECT * FROM student";
ResultSet rs = stmt.executeQuery(sql2);
while (rs.next()) {
int id = rs.getInt("studId");
String fname = rs.getString("fname");
String lname = rs.getString("lname");
String email = rs.getString("email");
String major = rs.getString("major");
System.out.printf("%-12d %-10s %-10s %-25s %-6s n", id, fname, lname, email, major);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
Demonstration
create statement object
SQL query
execute a query, returns a ResultSet object
loop over results
fetch results from ResultSet object into Java variables
format and print results
close the result set and the statement
Demonstration
Improve the structure of your program
make a global connection
move connecting code into a separate method
call your connect method from the constructor
Improve the structure of your program
separate database
operations into
methods
Improve the structure of your program
call operational methods
from main() as needed
Improve your program much more
• Create a pretty Graphical User Interface
– Swing: JPanel, JTable, …
• Make Java classes for your database entities
• Use suitable Design Pattern
– Singleton pattern
Improve your program much more
Improve your program much more
Security Issue
SQL Injection
Prepared Statements
• A PreparedStatement object
holds precompiled SQL statements.
• Use this object for statements you want to
execute more than once.
• A prepared statement can contain variables
that you supply each time you execute the
statement.
How to Create a Prepared Statement
1.Register the driver and create the database
connection.
2.Create the prepared statement, identifying
variables with a question mark (?).
PreparedStatement pstmt =
conn.prepareStatement("UPDATE student
SET email = ? WHERE studID = ?");
PreparedStatement pstmt =
conn.prepareStatement("SELECT deptName FROM
department WHERE deptCode = ?");
How to Execute a Prepared Statement
1. Supply values for the variables.
2. Execute the statement.
pstmt.setXXX(index, value);
pstmt.executeQuery();
pstmt.executeUpdate();
PreparedStatement pstmt =
conn.prepareStatement("UPDATE student
SET email = ? WHERE studID = ?");
pstmt.setString(1, "abcd@gmail.com");
pstmt.setInt(2, studId);
pstmt.executeUpdate();
Demonstration
SQL query with placeholders
Supply values to the placeholders
Create PreparedStatement object
Execute the prepared update statement
Much more still to do
• Transaction Management
• Scrollable Result Set
• Updatable Result Set
• Callable Statements
• Metadata
– DatabaseMetaData
– ResultSetMetaData
JDBC Resources
• JDBC Tutorials
– http://www.oracle.com/technetwork/java/index-141229.html
• JDBC Online Courses
– http://www.oracle.com/technetwork/java/index-137757.html
• JDBC Books
– http://www.oracle.com/technetwork/java/index-142052.html
Database Programming Approaches
• Embedded SQL Approach
– Embedded SQL ( C language)
– SQLJ (Java language)
• Library of Function Calls Approach.
– JDBC
– SQL/CLI
• Database Programming Language Approach
– Stored Procedures
Stored Procedures
Persistent Stored Modules
Stored Procedures
Views
Way to register queries inside DBMS
Stored Procedures
Way to register code inside DBMS
Stored Procedures
• What is stored procedure?
– Piece of code stored inside the DBMS
– SQL allows you to define procedures and functions and
store them inside DBMS
• Advantages
– Reusability: do not need to write the code again and again
– Programming language-like environment
• Assignment, Loop, For, IF statements
– Call it whenever needed
• From select statement, another procedure, or another function
SQL/PSM
• SQL/Persistent Stored Modules
• ISO standard defining an extension of SQL with a procedural
language for use in stored procedures.
PL/SQL Transact-SQL
SQL PL
MySQL
stored procedures
PL/pgSQL
Stored Procedures in PostgreSQL
• PostgreSQL allows user-defined functions to be
written in other languages besides SQL and C:
– PL/pgSQL
– PL/Perl
– PL/Tcl
– PL/Python
PL/pgSQL
• PL/pgSQL: Procedural Language postgreSQL
• The design goals of PL/pgSQL were to create a
procedural language that
– can be used to create functions and trigger procedures,
– adds control structures to the SQL language,
– can perform complex computations,
– inherits all user-defined types, functions, and operators,
– is easy to use.
Structure of PL/pgSQL functions
CREATE [OR REPLACE] FUNCTION <functionName> (<paramList>)
RETURNS [<type> | VOID]
AS $$
[ DECLARE
<declarations> ]
BEGIN
<functionBody>;
END;
$$ LANGUAGE plpgsql;
If exists, then drop it and
create it again
A parameter in the paramList is specified as:
<name> <mode> <type>
Mode:
IN input parameter (default)
OUT output parameter
INOUT input and output parameter
Example 1
CREATE FUNCTION remove_emp(empID INTEGER) RETURNS void AS $$
BEGIN
DELETE FROM employee
WHERE employee.emp_id = empID ;
RETURN ;
END;
$$ LANGUAGE plpgsql;
Function name Parameter list nothing to return
RETURN means exit the function
parameter used inside SQL
SELECT remove_emp(110);
Stored procedures can be called:
• from SQL
• from other functions
• from applications (JDBC CallableStatement)
Declarations
• Examples
quantity INTEGER DEFAULT 32;
url VARCHAR := 'http://mysite.com';
user_id CONSTANT INTEGER := 10;
name [CONSTANT] type [NOT NULL] [{DEFAULT | := } expression];
Control Structures (Conditionals)
IF boolean-expression THEN
statements
END IF;
IF-THEN
IF boolean-expression THEN
statements
ELSE
statements
END IF;
IF-THEN-ELSE
IF boolean-expression THEN
statements
[ ELSIF boolean-expression THEN
statements
[ ELSIF boolean-expression THEN
statements
...]]
[ ELSE
statements ]
END IF;
IF-THEN-ELSIF
CASE search-expression
WHEN expression [, expression [ ... ]] THEN
statements
[ WHEN expression [, expression [ ... ]] THEN
statements
... ]
[ ELSE
statements ]
END CASE;
Simple CASE
CASE
WHEN boolean-expression THEN
statements
[ WHEN boolean-expression THEN
statements
... ]
[ ELSE
statements ]
END CASE;
Searched CASE
Control Structures (Loops)
[ <<label>> ]
LOOP
statements
END LOOP [ label ];
LOOP
EXIT [ label ] [ WHEN boolean-expression ];
EXIT
[ <<label>> ]
WHILE boolean-expression LOOP
statements
END LOOP [ label ];
WHILE
CONTINUE [ label ] [ WHEN boolean-expression ];
CONTINUE
FOR (Integer Variant)
[ <<label>> ]
FOR name IN [ REVERSE ] expression .. expression [ BY expression ] LOOP
statements
END LOOP [ label ];
[ <<label>> ]
FOR target IN query LOOP
statements
END LOOP [ label ];
FOR (Query Results Variant)
Example 2
• Raise the salary of
employees of a given
department by a
certain ratio.
– dept_id = 1
– ratio = 0.10
• Keep track of salary
changes.
emp_id emp_name salary dept_id
101 John 1000 1
102 Jack 1100 1
103 Smith 1200 2
104 Walter 1000 2
105 Mike 1500 2
106 Sarah 1600 3
107 Judie 1250 3
emp_id change_date old_salary new_salary
Employee
Salary_History
Example 2
CREATE FUNCTION raise_salary(deptID INTEGER, ratio REAL)
RETURNS void AS $$
DECLARE
oldSal REAL; newSal REAL;
curs1 CURSOR FOR
SELECT * FROM employee
WHERE employee.dept_id = deptID;
BEGIN
FOR var IN curs1 LOOP
oldSal := var.salary;
newSal := oldSal + oldSal * ratio;
UPDATE employee
SET salary = newSal
WHERE CURRENT OF curs1;
INSERT INTO salary_history
VALUES(var.emp_id, current_date, oldSal, newSal);
END LOOP;
RETURN;
END ;
$$ LANGUAGE plpgsql;
Use cursor to iterate rows
Define a cursor that references
the input parameter
variable assignments
Declaration
Section
update the row which the
cursor is positioned on
Implicit row-variable
parameter used inside Cursor
FunctionBody
Runemp_id emp_name salary dept_id
101 John 1000 1
102 Jack 1100 1
103 Smith 1200 2
104 Walter 1000 2
105 Mike 1500 2
106 Sarah 1600 3
107 Judie 1250 3
SELECT raise_salary(1, 0.10);
emp_id change_date old_salary new_salary
emp_id emp_name salary dept_id
101 John 1100 1
102 Jack 1210 1
103 Smith 1200 2
104 Walter 1000 2
105 Mike 1500 2
106 Sarah 1600 3
107 Judie 1250 3
emp_id emp_name salary dept_id
101 John 1100 1
102 Jack 1210 1
103 Smith 1380 2
104 Walter 1150 2
105 Mike 1725 2
106 Sarah 1600 3
107 Judie 1250 3
emp_id change_date old_salary new_salary
101 2015-04-06 1000 1100
102 2015-04-06 1100 1210
emp_id change_date old_salary new_salary
101 2015-04-06 1000 1100
102 2015-04-06 1100 1210
103 2015-04-07 1200 1380
104 2015-04-07 1000 1150
105 2015-04-07 1500 1725
SELECT raise_salary(2, 0.15);
Employee Salary_History
Much more still to do
• Exception handling
• Complex data types
– Arrays, Tables
• User defined data types
– (Object-Relational Model)
• Triggers
– (Active Databases)
References
• PostgreSQL Documentation
PL/pgSQL - SQL Procedural Language
– http://www.postgresql.org/docs/8.3/static/plpgsql.html
• Fundamentals of Database Systems, Elmasri and
Navathe, 6th Edition, Chapter 13
 Some slides are adopted from:
– www.cse.lehigh.edu/~glennb/oose/ppt/JDBC.ppt
Thank you

Contenu connexe

Tendances

Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and Objects
Ranel Padon
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]
Ravindra Raju Kolahalam
 
Instance based learning
Instance based learningInstance based learning
Instance based learning
Slideshare
 

Tendances (20)

Data Mining Techniques
Data Mining TechniquesData Mining Techniques
Data Mining Techniques
 
Sms spam-detection
Sms spam-detectionSms spam-detection
Sms spam-detection
 
Consistency in NoSQL
Consistency in NoSQLConsistency in NoSQL
Consistency in NoSQL
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
5.3 mining sequential patterns
5.3 mining sequential patterns5.3 mining sequential patterns
5.3 mining sequential patterns
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and Objects
 
Introduction to pandas
Introduction to pandasIntroduction to pandas
Introduction to pandas
 
DBSCAN : A Clustering Algorithm
DBSCAN : A Clustering AlgorithmDBSCAN : A Clustering Algorithm
DBSCAN : A Clustering Algorithm
 
Recursive Descent Parsing
Recursive Descent Parsing  Recursive Descent Parsing
Recursive Descent Parsing
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Classification and Clustering
Classification and ClusteringClassification and Clustering
Classification and Clustering
 
Violence-Detection-using-Transder-Learning.pptx
Violence-Detection-using-Transder-Learning.pptxViolence-Detection-using-Transder-Learning.pptx
Violence-Detection-using-Transder-Learning.pptx
 
05 Clustering in Data Mining
05 Clustering in Data Mining05 Clustering in Data Mining
05 Clustering in Data Mining
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
Instance based learning
Instance based learningInstance based learning
Instance based learning
 
Data Mining Techniques
Data Mining TechniquesData Mining Techniques
Data Mining Techniques
 

En vedette

Revisiting Co-Processing for Hash Joins on the Coupled Cpu-GPU Architecture
Revisiting Co-Processing for Hash Joins on the CoupledCpu-GPU ArchitectureRevisiting Co-Processing for Hash Joins on the CoupledCpu-GPU Architecture
Revisiting Co-Processing for Hash Joins on the Coupled Cpu-GPU Architecture
mohamedragabslideshare
 
[Harvard CS264] 10a - Easy, Effective, Efficient: GPU Programming in Python w...
[Harvard CS264] 10a - Easy, Effective, Efficient: GPU Programming in Python w...[Harvard CS264] 10a - Easy, Effective, Efficient: GPU Programming in Python w...
[Harvard CS264] 10a - Easy, Effective, Efficient: GPU Programming in Python w...
npinto
 
Jena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaJena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for Java
Aleksander Pohl
 

En vedette (20)

SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
Jena Programming
Jena ProgrammingJena Programming
Jena Programming
 
VNSISPL_DBMS_Concepts_ch4
VNSISPL_DBMS_Concepts_ch4VNSISPL_DBMS_Concepts_ch4
VNSISPL_DBMS_Concepts_ch4
 
Revisiting Co-Processing for Hash Joins on the Coupled Cpu-GPU Architecture
Revisiting Co-Processing for Hash Joins on the CoupledCpu-GPU ArchitectureRevisiting Co-Processing for Hash Joins on the CoupledCpu-GPU Architecture
Revisiting Co-Processing for Hash Joins on the Coupled Cpu-GPU Architecture
 
Ims11 ims13 application programming enhancements - IMS UG May 2014 Sydney & ...
Ims11  ims13 application programming enhancements - IMS UG May 2014 Sydney & ...Ims11  ims13 application programming enhancements - IMS UG May 2014 Sydney & ...
Ims11 ims13 application programming enhancements - IMS UG May 2014 Sydney & ...
 
Dotnet difference questions & answers Compiled-1
Dotnet difference questions & answers Compiled-1Dotnet difference questions & answers Compiled-1
Dotnet difference questions & answers Compiled-1
 
Dynamic query
Dynamic queryDynamic query
Dynamic query
 
[Harvard CS264] 10a - Easy, Effective, Efficient: GPU Programming in Python w...
[Harvard CS264] 10a - Easy, Effective, Efficient: GPU Programming in Python w...[Harvard CS264] 10a - Easy, Effective, Efficient: GPU Programming in Python w...
[Harvard CS264] 10a - Easy, Effective, Efficient: GPU Programming in Python w...
 
Sql
SqlSql
Sql
 
Jena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaJena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for Java
 
Dbms ii mca-ch7-sql-2013
Dbms ii mca-ch7-sql-2013Dbms ii mca-ch7-sql-2013
Dbms ii mca-ch7-sql-2013
 
Java and OWL
Java and OWLJava and OWL
Java and OWL
 
Visual Logic User Guide
Visual Logic User GuideVisual Logic User Guide
Visual Logic User Guide
 
Dynamic query forms for database queries
Dynamic query forms for database queriesDynamic query forms for database queries
Dynamic query forms for database queries
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
 
dynamic query forms for data base querys
dynamic query forms for data base querysdynamic query forms for data base querys
dynamic query forms for data base querys
 
Sql
SqlSql
Sql
 
Importance of Database in Library
Importance of Database in LibraryImportance of Database in Library
Importance of Database in Library
 
Introduction to Business Statistics
Introduction to Business StatisticsIntroduction to Business Statistics
Introduction to Business Statistics
 

Similaire à Database Programming Techniques

Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
Staples
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 

Similaire à Database Programming Techniques (20)

Jdbc
JdbcJdbc
Jdbc
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
JDBC
JDBCJDBC
JDBC
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
Lecture17
Lecture17Lecture17
Lecture17
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc
JdbcJdbc
Jdbc
 

Plus de Raji Ghawi

Plus de Raji Ghawi (11)

Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
 
Java and XML
Java and XMLJava and XML
Java and XML
 
Java and SPARQL
Java and SPARQLJava and SPARQL
Java and SPARQL
 
SPARQL
SPARQLSPARQL
SPARQL
 
XQuery
XQueryXQuery
XQuery
 
XPath
XPathXPath
XPath
 
Ontology-based Cooperation of Information Systems
Ontology-based Cooperation of Information SystemsOntology-based Cooperation of Information Systems
Ontology-based Cooperation of Information Systems
 
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
OWSCIS: Ontology and Web Service based Cooperation of Information SourcesOWSCIS: Ontology and Web Service based Cooperation of Information Sources
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
 
Coopération des Systèmes d'Informations basée sur les Ontologies
Coopération des Systèmes d'Informations basée sur les OntologiesCoopération des Systèmes d'Informations basée sur les Ontologies
Coopération des Systèmes d'Informations basée sur les Ontologies
 
Building Ontologies from Multiple Information Sources
Building Ontologies from Multiple Information SourcesBuilding Ontologies from Multiple Information Sources
Building Ontologies from Multiple Information Sources
 
Database-to-Ontology Mapping Generation for Semantic Interoperability
Database-to-Ontology Mapping Generation for Semantic InteroperabilityDatabase-to-Ontology Mapping Generation for Semantic Interoperability
Database-to-Ontology Mapping Generation for Semantic Interoperability
 

Dernier

Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
amitlee9823
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
amitlee9823
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
shivangimorya083
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
AroojKhan71
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
amitlee9823
 
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get CytotecAbortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Riyadh +966572737505 get cytotec
 

Dernier (20)

Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signals
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfAccredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
 
Sampling (random) method and Non random.ppt
Sampling (random) method and Non random.pptSampling (random) method and Non random.ppt
Sampling (random) method and Non random.ppt
 
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort ServiceBDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
 
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Research
 
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get CytotecAbortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
 

Database Programming Techniques

  • 1. Database Programming Techniques CMPS 277 Raji Ghawi rg31@aub.edu.lb 7 April 2015
  • 2. Interaction with Databases • Interactive interface – SQL commands typed directly into a monitor – Execute file of commands • @<filename> • Application programs or database applications – Used as canned transactions by the end users access a database – May have Web interface – Host language: Java, C/C++/C# , … – Database language: SQL
  • 3. Database Programming Approaches • Embedded SQL Approach – Embedded SQL ( C language) – SQLJ (Java language) • Library of Function Calls Approach. – JDBC – SQL/CLI • Database Programming Language Approach – Stored Procedures
  • 4. Database Programming Approaches • Embedded SQL Approach – Embedded SQL ( C language) – SQLJ (Java language) • Library of Function Calls Approach. – JDBC – SQL/CLI • Database Programming Language Approach – Stored Procedures
  • 5. JDBC One API to Access Them All
  • 6. Introduction • JDBC: Java DataBase Connectivity • JDBC is a standard interface that lets you access virtually any tabular data source from the Java programming language – relational databases, spreadsheets, flat files • The JDBC classes and interfaces are in the java.sql package
  • 7. General Architecture Java Application or Applet JDBC Driver Manager Oracle Driver MySQL Driver PostgreSQL Driver Oracle PostgreSQLMySQL • The Driver Manager provides a consistent layer between your Java application and back-end database.
  • 8. • Is an interpreter that translates JDBC method calls to vendor- specific database commands • Implements interfaces in java.sql • Can also provide a vendor’s extensions to the JDBC standard Driver JDBC calls Database commands Database A JDBC Driver
  • 9. Query Close Connect Process results Overview of Querying a Database With JDBC
  • 10. Register the driver Connect to the database Stage 1: Connect Query Close Connect Process results
  • 11. 1. Register the driver. 2. Connect to the database. DriverManager.registerDriver(new org.postgresql.Driver()); Connection conn = DriverManager.getConnection (URL, userid, password); Connection conn = DriverManager.getConnection ("jdbc:postgresql://localhost/University", "xxxx", "xxxx"); How to Make the Connection
  • 12. Using Connection java.sql.Connection Creating Statement Transaction Management Get database metadata Conneciton related createStatment() prepareStatment(String) prepareCall(String) commit() rollback() getMetaData() close() isClosed()
  • 13. List of JDBC Drivers DBMS Driver / URL PostgreSQL org.postgresql.Driver jdbc:postgresql://[host]/[DB] MySQL com.mysql.jdbc.Driver jdbc:mysql://[host]/[DB] Oracle oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@[host]:[port]:[db] jdbc:oracle:oci:@[host]:[port]:[db] SQL Server com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc:sqlserver://[host];databaseName=[db]; ODBC bridge sun.jdbc.odbc.JdbcOdbcDriver jdbc:odbc:[db]
  • 14. Demonstration import java.sql.*; public class MyDBApp1 { public static void main(String[] args) { String url = "jdbc:postgresql://localhost/University"; String username = "xxxx"; String passwd = "xxxx"; try { Class.forName("org.postgresql.Driver"); Connection connection = DriverManager.getConnection(url, username, passwd); // do something with connection } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
  • 15. Create a statement Query the database Stage 2: Query Query Close Connect Process results
  • 16. The Statement Object • A Statement object sends your SQL statement to the database. • You need an active connection to create a JDBC statement. • Statement has three methods to execute a SQL statement: – executeQuery() for SELECT statements – executeUpdate() for INSERT, UPDATE, DELETE, or DDL statements – execute() for either type of statement
  • 17. 1. Create an empty statement object. 2. Execute the statement. Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(statement); int count = stmt.executeUpdate(statement); boolean isquery = stmt.execute(statement); How to Query the Database
  • 18. Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery ("SELECT fname, lname FROM student"); Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("DELETE FROM student WHERE studid = '201231521'"); Querying the Database: Examples • Execute a select statement. • Execute a delete statement.
  • 19. Step through the results Assign results to Java variables Stage 3: Process the Results Close Connect Process results Query
  • 20. The ResultSet Object • JDBC returns the results of a query in a ResultSet object. • A ResultSet maintains a cursor pointing to its current row of data. • Use next() to step through the result set row by row. • getString(), getInt(), and so on assign each value to a Java variable.
  • 21. 1. Step through the result set. 2. Use getXXX() to get each column value. while (rset.next()) { … } String val = rset.getString(colname); while (rset.next()) { String fname = rset.getString("fname"); String email = rset.getString("email"); // Process or display the data } String val = rset.getString(colIndex); How to Process the Results
  • 22. while (rset.next()) { String email = rset.getString("email"); if (rset.wasNull() { … // Handle null value } …} How to Handle SQL Null Values • Java primitive types cannot have null values. • Do not use a primitive type when your query might return a SQL null. • Use ResultSet.wasNull() to determine whether a column has a null value.
  • 23. Mapping Database Types to Java Types • ResultSet maps database types to Java types. ResultSet rset = stmt.executeQuery ("SELECT id, birth_date, name FROM student"); int id = rset.getInt(1); Date birthdate = rset.getDate(2); String name = rset.getString(3); Column Name Type id INTEGER birthdate DATE name VARCHAR
  • 24. JDBC Type Java Type BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT DOUBLE double BINARY VARBINARY LONGVARBINARY byte[] CHAR VARCHAR LONGVARCHAR String Mapping Database Types to Java Types JDBC Type Java Type NUMERIC DECIMAL BigDecimal DATE java.sql.Date TIME TIMESTAMP java.sql.Timestamp CLOB Clob* BLOB Blob* ARRAY Array* STRUCT Struct* REF Ref* JAVA_OBJECT underlying Java class * SQL3 data type supported in JDBC 2.0
  • 25. Close the result set Close the statement Close the connection Stage 4: Close Close Connect Query Process Results
  • 26. 1. Close the ResultSet object. 2. Close the Statement object. 3. Close the connection. rset.close(); stmt.close(); conn.close(); How to Close the Connection
  • 27. Demonstration public static void main(String[] args) { String url = "jdbc:postgresql://localhost/University"; String username = "xxxx"; String passwd = "xxxx"; try { Class.forName("org.postgresql.Driver"); Connection connection = DriverManager.getConnection(url, username, passwd); Statement stmt = connection.createStatement(); String sql2 = "SELECT * FROM student"; ResultSet rs = stmt.executeQuery(sql2); while (rs.next()) { int id = rs.getInt("studId"); String fname = rs.getString("fname"); String lname = rs.getString("lname"); String email = rs.getString("email"); String major = rs.getString("major"); System.out.printf("%-12d %-10s %-10s %-25s %-6s n", id, fname, lname, email, major); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
  • 28. Demonstration create statement object SQL query execute a query, returns a ResultSet object loop over results fetch results from ResultSet object into Java variables format and print results close the result set and the statement
  • 30. Improve the structure of your program make a global connection move connecting code into a separate method call your connect method from the constructor
  • 31. Improve the structure of your program separate database operations into methods
  • 32. Improve the structure of your program call operational methods from main() as needed
  • 33. Improve your program much more • Create a pretty Graphical User Interface – Swing: JPanel, JTable, … • Make Java classes for your database entities • Use suitable Design Pattern – Singleton pattern
  • 34. Improve your program much more
  • 35. Improve your program much more
  • 37. Prepared Statements • A PreparedStatement object holds precompiled SQL statements. • Use this object for statements you want to execute more than once. • A prepared statement can contain variables that you supply each time you execute the statement.
  • 38. How to Create a Prepared Statement 1.Register the driver and create the database connection. 2.Create the prepared statement, identifying variables with a question mark (?). PreparedStatement pstmt = conn.prepareStatement("UPDATE student SET email = ? WHERE studID = ?"); PreparedStatement pstmt = conn.prepareStatement("SELECT deptName FROM department WHERE deptCode = ?");
  • 39. How to Execute a Prepared Statement 1. Supply values for the variables. 2. Execute the statement. pstmt.setXXX(index, value); pstmt.executeQuery(); pstmt.executeUpdate(); PreparedStatement pstmt = conn.prepareStatement("UPDATE student SET email = ? WHERE studID = ?"); pstmt.setString(1, "abcd@gmail.com"); pstmt.setInt(2, studId); pstmt.executeUpdate();
  • 40. Demonstration SQL query with placeholders Supply values to the placeholders Create PreparedStatement object Execute the prepared update statement
  • 41. Much more still to do • Transaction Management • Scrollable Result Set • Updatable Result Set • Callable Statements • Metadata – DatabaseMetaData – ResultSetMetaData
  • 42. JDBC Resources • JDBC Tutorials – http://www.oracle.com/technetwork/java/index-141229.html • JDBC Online Courses – http://www.oracle.com/technetwork/java/index-137757.html • JDBC Books – http://www.oracle.com/technetwork/java/index-142052.html
  • 43. Database Programming Approaches • Embedded SQL Approach – Embedded SQL ( C language) – SQLJ (Java language) • Library of Function Calls Approach. – JDBC – SQL/CLI • Database Programming Language Approach – Stored Procedures
  • 45. Stored Procedures Views Way to register queries inside DBMS Stored Procedures Way to register code inside DBMS
  • 46. Stored Procedures • What is stored procedure? – Piece of code stored inside the DBMS – SQL allows you to define procedures and functions and store them inside DBMS • Advantages – Reusability: do not need to write the code again and again – Programming language-like environment • Assignment, Loop, For, IF statements – Call it whenever needed • From select statement, another procedure, or another function
  • 47. SQL/PSM • SQL/Persistent Stored Modules • ISO standard defining an extension of SQL with a procedural language for use in stored procedures. PL/SQL Transact-SQL SQL PL MySQL stored procedures PL/pgSQL
  • 48. Stored Procedures in PostgreSQL • PostgreSQL allows user-defined functions to be written in other languages besides SQL and C: – PL/pgSQL – PL/Perl – PL/Tcl – PL/Python
  • 49. PL/pgSQL • PL/pgSQL: Procedural Language postgreSQL • The design goals of PL/pgSQL were to create a procedural language that – can be used to create functions and trigger procedures, – adds control structures to the SQL language, – can perform complex computations, – inherits all user-defined types, functions, and operators, – is easy to use.
  • 50. Structure of PL/pgSQL functions CREATE [OR REPLACE] FUNCTION <functionName> (<paramList>) RETURNS [<type> | VOID] AS $$ [ DECLARE <declarations> ] BEGIN <functionBody>; END; $$ LANGUAGE plpgsql; If exists, then drop it and create it again A parameter in the paramList is specified as: <name> <mode> <type> Mode: IN input parameter (default) OUT output parameter INOUT input and output parameter
  • 51. Example 1 CREATE FUNCTION remove_emp(empID INTEGER) RETURNS void AS $$ BEGIN DELETE FROM employee WHERE employee.emp_id = empID ; RETURN ; END; $$ LANGUAGE plpgsql; Function name Parameter list nothing to return RETURN means exit the function parameter used inside SQL SELECT remove_emp(110); Stored procedures can be called: • from SQL • from other functions • from applications (JDBC CallableStatement)
  • 52. Declarations • Examples quantity INTEGER DEFAULT 32; url VARCHAR := 'http://mysite.com'; user_id CONSTANT INTEGER := 10; name [CONSTANT] type [NOT NULL] [{DEFAULT | := } expression];
  • 53. Control Structures (Conditionals) IF boolean-expression THEN statements END IF; IF-THEN IF boolean-expression THEN statements ELSE statements END IF; IF-THEN-ELSE IF boolean-expression THEN statements [ ELSIF boolean-expression THEN statements [ ELSIF boolean-expression THEN statements ...]] [ ELSE statements ] END IF; IF-THEN-ELSIF CASE search-expression WHEN expression [, expression [ ... ]] THEN statements [ WHEN expression [, expression [ ... ]] THEN statements ... ] [ ELSE statements ] END CASE; Simple CASE CASE WHEN boolean-expression THEN statements [ WHEN boolean-expression THEN statements ... ] [ ELSE statements ] END CASE; Searched CASE
  • 54. Control Structures (Loops) [ <<label>> ] LOOP statements END LOOP [ label ]; LOOP EXIT [ label ] [ WHEN boolean-expression ]; EXIT [ <<label>> ] WHILE boolean-expression LOOP statements END LOOP [ label ]; WHILE CONTINUE [ label ] [ WHEN boolean-expression ]; CONTINUE FOR (Integer Variant) [ <<label>> ] FOR name IN [ REVERSE ] expression .. expression [ BY expression ] LOOP statements END LOOP [ label ]; [ <<label>> ] FOR target IN query LOOP statements END LOOP [ label ]; FOR (Query Results Variant)
  • 55. Example 2 • Raise the salary of employees of a given department by a certain ratio. – dept_id = 1 – ratio = 0.10 • Keep track of salary changes. emp_id emp_name salary dept_id 101 John 1000 1 102 Jack 1100 1 103 Smith 1200 2 104 Walter 1000 2 105 Mike 1500 2 106 Sarah 1600 3 107 Judie 1250 3 emp_id change_date old_salary new_salary Employee Salary_History
  • 56. Example 2 CREATE FUNCTION raise_salary(deptID INTEGER, ratio REAL) RETURNS void AS $$ DECLARE oldSal REAL; newSal REAL; curs1 CURSOR FOR SELECT * FROM employee WHERE employee.dept_id = deptID; BEGIN FOR var IN curs1 LOOP oldSal := var.salary; newSal := oldSal + oldSal * ratio; UPDATE employee SET salary = newSal WHERE CURRENT OF curs1; INSERT INTO salary_history VALUES(var.emp_id, current_date, oldSal, newSal); END LOOP; RETURN; END ; $$ LANGUAGE plpgsql; Use cursor to iterate rows Define a cursor that references the input parameter variable assignments Declaration Section update the row which the cursor is positioned on Implicit row-variable parameter used inside Cursor FunctionBody
  • 57. Runemp_id emp_name salary dept_id 101 John 1000 1 102 Jack 1100 1 103 Smith 1200 2 104 Walter 1000 2 105 Mike 1500 2 106 Sarah 1600 3 107 Judie 1250 3 SELECT raise_salary(1, 0.10); emp_id change_date old_salary new_salary emp_id emp_name salary dept_id 101 John 1100 1 102 Jack 1210 1 103 Smith 1200 2 104 Walter 1000 2 105 Mike 1500 2 106 Sarah 1600 3 107 Judie 1250 3 emp_id emp_name salary dept_id 101 John 1100 1 102 Jack 1210 1 103 Smith 1380 2 104 Walter 1150 2 105 Mike 1725 2 106 Sarah 1600 3 107 Judie 1250 3 emp_id change_date old_salary new_salary 101 2015-04-06 1000 1100 102 2015-04-06 1100 1210 emp_id change_date old_salary new_salary 101 2015-04-06 1000 1100 102 2015-04-06 1100 1210 103 2015-04-07 1200 1380 104 2015-04-07 1000 1150 105 2015-04-07 1500 1725 SELECT raise_salary(2, 0.15); Employee Salary_History
  • 58. Much more still to do • Exception handling • Complex data types – Arrays, Tables • User defined data types – (Object-Relational Model) • Triggers – (Active Databases)
  • 59. References • PostgreSQL Documentation PL/pgSQL - SQL Procedural Language – http://www.postgresql.org/docs/8.3/static/plpgsql.html • Fundamentals of Database Systems, Elmasri and Navathe, 6th Edition, Chapter 13  Some slides are adopted from: – www.cse.lehigh.edu/~glennb/oose/ppt/JDBC.ppt

Notes de l'éditeur

  1. The DEFAULT clause, if given, specifies the initial value assigned to the variable when the block is entered. If the DEFAULT clause is not given then the variable is initialized to the SQL null value. The CONSTANT option prevents the variable from being assigned to after initialization, so that its value will remain constant for the duration of the block. If NOT NULL is specified, an assignment of a null value results in a run-time error. All variables declared as NOT NULL must have a nonnull default value specified.