SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PPT
Using the set operators
Syed Zaid Irshad
 
PPT
Object and class relationships
Pooja mittal
 
PPT
Nested Queries-SQL.ppt
JayavarapuKarthikJ1
 
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
PPTX
Inheritance in JAVA PPT
Pooja Jaiswal
 
PPTX
android sqlite
Deepa Rani
 
PPTX
Relational algebra ppt
GirdharRatne
 
PPTX
JAVA AWT
shanmuga rajan
 
PDF
PostgreSQL Tutorial For Beginners | Edureka
Edureka!
 
PPTX
Lecture_7-Encapsulation in Java.pptx
ShahinAhmed49
 
PDF
Triggers and active database
BalaMuruganSamuthira
 
PPTX
Basics of Denial of Service Attacks
Hansa Nidushan
 
PPTX
Buffer and scanner
Arif Ullah
 
PPTX
SQL(DDL & DML)
Sharad Dubey
 
PPT
14. Query Optimization in DBMS
koolkampus
 
PDF
Android Location and Maps
Jussi Pohjolainen
 
PPTX
Presentation on Relational Schema (Database)
Salim Hosen
 
PPTX
Object model
James Wong
 
PPTX
Java abstract class & abstract methods
Shubham Dwivedi
 
PPT
Java Notes
Abhishek Khune
 
Using the set operators
Syed Zaid Irshad
 
Object and class relationships
Pooja mittal
 
Nested Queries-SQL.ppt
JayavarapuKarthikJ1
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Inheritance in JAVA PPT
Pooja Jaiswal
 
android sqlite
Deepa Rani
 
Relational algebra ppt
GirdharRatne
 
JAVA AWT
shanmuga rajan
 
PostgreSQL Tutorial For Beginners | Edureka
Edureka!
 
Lecture_7-Encapsulation in Java.pptx
ShahinAhmed49
 
Triggers and active database
BalaMuruganSamuthira
 
Basics of Denial of Service Attacks
Hansa Nidushan
 
Buffer and scanner
Arif Ullah
 
SQL(DDL & DML)
Sharad Dubey
 
14. Query Optimization in DBMS
koolkampus
 
Android Location and Maps
Jussi Pohjolainen
 
Presentation on Relational Schema (Database)
Salim Hosen
 
Object model
James Wong
 
Java abstract class & abstract methods
Shubham Dwivedi
 
Java Notes
Abhishek Khune
 

Viewers also liked (20)

PPTX
SQL, Embedded SQL, Dynamic SQL and SQLJ
Dharita Chokshi
 
PPT
SQL / PL
srijanani2030
 
PPTX
Jena Programming
Myungjin Lee
 
PPT
VNSISPL_DBMS_Concepts_ch4
sriprasoon
 
PPTX
Revisiting Co-Processing for Hash Joins on the Coupled Cpu-GPU Architecture
mohamedragabslideshare
 
PDF
Ims11 ims13 application programming enhancements - IMS UG May 2014 Sydney & ...
Robert Hain
 
PDF
Dotnet difference questions & answers Compiled-1
Umar Ali
 
PPTX
Dynamic query
LearningTech
 
PDF
[Harvard CS264] 10a - Easy, Effective, Efficient: GPU Programming in Python w...
npinto
 
PPTX
Sql
Mahfuz1061
 
PDF
Jena – A Semantic Web Framework for Java
Aleksander Pohl
 
PPT
Dbms ii mca-ch7-sql-2013
Prosanta Ghosh
 
PPTX
Java and OWL
Raji Ghawi
 
PDF
Visual Logic User Guide
Programming Techniques and Algorithms
 
DOCX
Dynamic query forms for database queries
LeMeniz Infotech
 
PPT
PL/SQL
Vaibhav0
 
PPT
dynamic query forms for data base querys
Siva Annapureddy
 
PDF
Sql
TestingGeeks
 
PPT
Introduction to Business Statistics
Atiq Rehman
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
Dharita Chokshi
 
SQL / PL
srijanani2030
 
Jena Programming
Myungjin Lee
 
VNSISPL_DBMS_Concepts_ch4
sriprasoon
 
Revisiting Co-Processing for Hash Joins on the Coupled Cpu-GPU Architecture
mohamedragabslideshare
 
Ims11 ims13 application programming enhancements - IMS UG May 2014 Sydney & ...
Robert Hain
 
Dotnet difference questions & answers Compiled-1
Umar Ali
 
Dynamic query
LearningTech
 
[Harvard CS264] 10a - Easy, Effective, Efficient: GPU Programming in Python w...
npinto
 
Jena – A Semantic Web Framework for Java
Aleksander Pohl
 
Dbms ii mca-ch7-sql-2013
Prosanta Ghosh
 
Java and OWL
Raji Ghawi
 
Visual Logic User Guide
Programming Techniques and Algorithms
 
Dynamic query forms for database queries
LeMeniz Infotech
 
PL/SQL
Vaibhav0
 
dynamic query forms for data base querys
Siva Annapureddy
 
Introduction to Business Statistics
Atiq Rehman
 
Ad

Similar to Database Programming Techniques (20)

PPTX
Jdbc Java Programming
chhaichivon
 
PPTX
Jdbc presentation
nrjoshiee
 
PPT
Jdbc oracle
yazidds2
 
PPT
3 database-jdbc(1)
hameedkhan2017
 
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
DOC
Java database connectivity notes for undergraduate
RameshPrasadBhatta2
 
PPTX
Database Access With JDBC
Dharani Kumar Madduri
 
PPT
Jdbc day-1
Soham Sengupta
 
PPT
Jdbc (database in java)
Maher Abdo
 
PDF
Java JDBC
Jussi Pohjolainen
 
PPT
JDBC Connectivity Model
kunj desai
 
PPTX
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
PPT
JDBC.ppt
Jayaprasanna4
 
PDF
Jdbc
mishaRani1
 
PPT
Jdbc
lathasiva
 
PPT
statement interface
khush_boo31
 
PPT
4. Database Connectivity using JDBC .ppt
HITENKHEMANI
 
PPTX
Jdbc ppt
AISHWARIYA1S
 
PPTX
JDBC ppt
Rohit Jain
 
Jdbc Java Programming
chhaichivon
 
Jdbc presentation
nrjoshiee
 
Jdbc oracle
yazidds2
 
3 database-jdbc(1)
hameedkhan2017
 
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
Java database connectivity notes for undergraduate
RameshPrasadBhatta2
 
Database Access With JDBC
Dharani Kumar Madduri
 
Jdbc day-1
Soham Sengupta
 
Jdbc (database in java)
Maher Abdo
 
JDBC Connectivity Model
kunj desai
 
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Indu32
 
JDBC.ppt
Jayaprasanna4
 
Jdbc
lathasiva
 
statement interface
khush_boo31
 
4. Database Connectivity using JDBC .ppt
HITENKHEMANI
 
Jdbc ppt
AISHWARIYA1S
 
JDBC ppt
Rohit Jain
 
Ad

More from Raji Ghawi (11)

PPTX
Java and XML Schema
Raji Ghawi
 
PPTX
Java and XML
Raji Ghawi
 
PPTX
Java and SPARQL
Raji Ghawi
 
PPTX
SPARQL
Raji Ghawi
 
PPTX
XQuery
Raji Ghawi
 
PPTX
XPath
Raji Ghawi
 
PPT
Ontology-based Cooperation of Information Systems
Raji Ghawi
 
PPT
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
Raji Ghawi
 
PPT
Coopération des Systèmes d'Informations basée sur les Ontologies
Raji Ghawi
 
PPT
Building Ontologies from Multiple Information Sources
Raji Ghawi
 
PPT
Database-to-Ontology Mapping Generation for Semantic Interoperability
Raji Ghawi
 
Java and XML Schema
Raji Ghawi
 
Java and XML
Raji Ghawi
 
Java and SPARQL
Raji Ghawi
 
SPARQL
Raji Ghawi
 
XQuery
Raji Ghawi
 
XPath
Raji Ghawi
 
Ontology-based Cooperation of Information Systems
Raji Ghawi
 
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
Raji Ghawi
 
Coopération des Systèmes d'Informations basée sur les Ontologies
Raji Ghawi
 
Building Ontologies from Multiple Information Sources
Raji Ghawi
 
Database-to-Ontology Mapping Generation for Semantic Interoperability
Raji Ghawi
 

Recently uploaded (20)

PPTX
04_Tamás Marton_Intuitech .pptx_AI_Barometer_2025
FinTech Belgium
 
PDF
apidays Singapore 2025 - Trustworthy Generative AI: The Role of Observability...
apidays
 
PDF
apidays Singapore 2025 - Streaming Lakehouse with Kafka, Flink and Iceberg by...
apidays
 
PDF
Technical-Report-GPS_GIS_RS-for-MSF-finalv2.pdf
KPycho
 
PDF
Business implication of Artificial Intelligence.pdf
VishalChugh12
 
PDF
The Best NVIDIA GPUs for LLM Inference in 2025.pdf
Tamanna36
 
PPTX
thid ppt defines the ich guridlens and gives the information about the ICH gu...
shaistabegum14
 
PDF
apidays Singapore 2025 - From API Intelligence to API Governance by Harsha Ch...
apidays
 
PPTX
ER_Model_with_Diagrams_Presentation.pptx
dharaadhvaryu1992
 
PDF
Optimizing Large Language Models with vLLM and Related Tools.pdf
Tamanna36
 
PDF
apidays Singapore 2025 - How APIs can make - or break - trust in your AI by S...
apidays
 
PPTX
美国史蒂文斯理工学院毕业证书{SIT学费发票SIT录取通知书}哪里购买
Taqyea
 
PDF
InformaticsPractices-MS - Google Docs.pdf
seshuashwin0829
 
PPTX
Powerful Uses of Data Analytics You Should Know
subhashenia
 
PPTX
big data eco system fundamentals of data science
arivukarasi
 
PPTX
b6057ea5-8e8c-4415-90c0-ed8e9666ffcd.pptx
Anees487379
 
PDF
Group 5_RMB Final Project on circular economy
pgban24anmola
 
PDF
apidays Singapore 2025 - The API Playbook for AI by Shin Wee Chuang (PAND AI)
apidays
 
PPTX
Aict presentation on dpplppp sjdhfh.pptx
vabaso5932
 
PDF
Data Science Course Certificate by Sigma Software University
Stepan Kalika
 
04_Tamás Marton_Intuitech .pptx_AI_Barometer_2025
FinTech Belgium
 
apidays Singapore 2025 - Trustworthy Generative AI: The Role of Observability...
apidays
 
apidays Singapore 2025 - Streaming Lakehouse with Kafka, Flink and Iceberg by...
apidays
 
Technical-Report-GPS_GIS_RS-for-MSF-finalv2.pdf
KPycho
 
Business implication of Artificial Intelligence.pdf
VishalChugh12
 
The Best NVIDIA GPUs for LLM Inference in 2025.pdf
Tamanna36
 
thid ppt defines the ich guridlens and gives the information about the ICH gu...
shaistabegum14
 
apidays Singapore 2025 - From API Intelligence to API Governance by Harsha Ch...
apidays
 
ER_Model_with_Diagrams_Presentation.pptx
dharaadhvaryu1992
 
Optimizing Large Language Models with vLLM and Related Tools.pdf
Tamanna36
 
apidays Singapore 2025 - How APIs can make - or break - trust in your AI by S...
apidays
 
美国史蒂文斯理工学院毕业证书{SIT学费发票SIT录取通知书}哪里购买
Taqyea
 
InformaticsPractices-MS - Google Docs.pdf
seshuashwin0829
 
Powerful Uses of Data Analytics You Should Know
subhashenia
 
big data eco system fundamentals of data science
arivukarasi
 
b6057ea5-8e8c-4415-90c0-ed8e9666ffcd.pptx
Anees487379
 
Group 5_RMB Final Project on circular economy
pgban24anmola
 
apidays Singapore 2025 - The API Playbook for AI by Shin Wee Chuang (PAND AI)
apidays
 
Aict presentation on dpplppp sjdhfh.pptx
vabaso5932
 
Data Science Course Certificate by Sigma Software University
Stepan Kalika
 

Database Programming Techniques

  • 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, "[email protected]"); 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

Editor's Notes

  • #53: 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.