Upload
others
View
13
Download
0
Embed Size (px)
Citation preview
JDBCJava Database Connectivity
Jaroslav Porubän, Peter Václavík
2008-2014
www.cde.sk
Introduction
Java API for accessing virtually any kind of tabular data
JDBC API is a Java interface for working with SQL
Establish a connection with a data source
Send queries and update statements to the data source
Process the results
Maydene Fisher, Jon Ellis, Jonathan Bruce: JDBC API Tutorial and Reference, 3rd Edition, Addison Wesley, 2003.
www.cde.sk
JDBC Two-tier Model
DS
JDBC
Java ApplicationClient Machine
DS proprietary protocol
Database Server
www.cde.sk
JDBC Three-tier Model
DS
JDBC
Java Application, Applet
or HTML BrowserClient Machine
DS proprietary protocol
Database Server
Application Server Server Machine (Business Logic)
HTTP, RMI, CORBA, or other calls
www.cde.sk
JDBC Architecture
Java application
JDBC Driver Manager
JDBC API
JDBC Driver API
Data Source
JDBC – ODBC
ODBC
Native
driver
Native
driver
JDBC
driver
Data Source
Java JDBC
driver
Java JDBC
driver
Data Source Data Source
DB
MiddleWare
Type 1 Type 2 Type 3 Type 4
www.cde.sk
Database URL
Used to make a connection to the databasejdbc:subprotocol_name:driver_dependant_dbname
Java DB (Derby)jdbc:derby://localhost/test
Oracle thin driverjdbc:oracle:thin:@localhost:1521:test
Pointbasejdbc:pointbase:server://localhost/test
MS SQLjdbc:jtds:sqlserver://localhost/test;tds=8.0
PostgreSQLjdbc:postgresql://localhost/test
www.cde.sk
Loading a Driver
Import package java.sqlimport java.sql.*;
Load Driver ClassClass.forName("org.apache.derby.jdbc.ClientDriver");
Driver class must be in a runtime classpath JDBC 4 supports driver auto-loading
The Class.forName() method
loads a class dynamically into memory class itself creates an instance of the driver
object and registers it with the DriverManager
www.cde.sk
Establishing a Connection
Making the Connection
String url =
"jdbc:derby://localhost/minesweeper";
String user = "minesweeper";
String password = "minesweeper";
Connection con = DriverManager.
getConnection(url, user, password);
www.cde.sk
Creating a Table
Use SQL Statement to create a
table
String query = "CREATE TABLE student ("
+ "id INT PRIMARY KEY,"
+ "firstname VARCHAR(32) NOT NULL,"
+ "surname VARCHAR(32) NOT NULL)";
Statement stmt = con.createStatement();
stmt.executeUpdate(query);
stm.close();
Example: CreateTest.java
www.cde.sk
Prepared Statements
The contained SQL is sent to the database and compiled or prepared beforehand
Depending on the DB engine, the SQL may be cached and reused even for a different PreparedStatement and most of the work is done by the DB engine rather than the driver
A PreparedStatement can take IN parameters, which act much like arguments to a method, for column values
PreparedStatement deal with data conversions that can be error prone in straight ahead, built on the fly SQL
www.cde.sk
Inserting Data
Use SQL PreparedStatement to
insert row in a tableString query = "INSERT INTO student "
+ "(id, firstname, surname) "
+ "VALUES (?, ?, ?)";
PreparedStatement stmt =
con.prepareStatement(query);
stmt.setInt(1, 1);
stmt.setString(2, "John");
stmt.setString(3, "Singleton");
stmt.executeUpdate();
stmt.close(); Example: InsertTest.java
www.cde.sk
Retrieving Values from Result Sets
Use SELECT to retrieve data from
databaseString query = "SELECT id, firstname, "
+ " surname FROM student";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
System.out.printf("%4d %-32s %-32s",
rs.getInt(1), rs.getString(2),
rs.getString(3));
}
rs.close();
stmt.close(); Example: SelectTest.java
www.cde.sk
Closing a Connection
Closing the Connection
Connection con = DriverManager.
getConnection(url, user, password);
Statement stmt = con.createStatement();
...
stm.close();
con.close();
www.cde.sk
Java 7 try-with-resources
J7 makes our life easier with the try-with-resources statements:
try(Connection c = dataSource.getConnection()) {
try (Statement st = c.createStatement()) {
try(ResultSet rs
= st.executeQuery(“some query”)) {
//Do stuff with the rs
}
try(RestulSet rs
= st.executeQuery(“some query”) {
//Do stuff with the rs
}
}
}
www.cde.sk
Java 7 try-with-resources
J7 makes our life easier with the try-with-resources statements (shorter):
try (Connection c = DriverManager
.getConnection(URL, USER, PASSWORD);
Statement st = c.createStatement();
ResultSet rs = st.executeQuery(DROP);
ResultSet rs2 = st.executeQuery(QUERY)) {
//do stuff, e.g. with rs and rs2
}
closes everything automatically!
www.cde.sk
Result Set and Database metadata
Once you have the Connection or ResultSet objects, you can obtain the metadata about the database or the query
This gives valuable information about the database that you are using or data that you are retrieving
ResultSetMetaData rsmd = rs.getMetaData();
DatabaseMetaData dbmd =
connection.getMetaData();
www.cde.sk
ResultSetMetaData
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
System.out.println("Column Name: " + rsmd.getColumnName(i));
System.out.println("Column Type: " + rsmd.getColumnTypeName(i));
}
rs.close();
Example: RSMDTest.java