Java Database Connectivity (JDBC) : CSIE33000 NT KP I Ij Network Programming in Java
Java Database Connectivity (JDBC) : CSIE33000 NT KP I Ij Network Programming in Java
Lecture 11:
Java Database
Connectivity (JDBC)
CSIE33000
Network
N t kPProgramming
i iin JJava
Introduction
Flat file access is not enough for complex
data management.
We need d to process information
f stored
d in
databases, especially relational databases.
Java Database Connectivity (JDBC) API is
designed for Java program to communicate
with relational databases.
databases
JDBC became part of the core Java with JDK
1.1
Shiow-yang Wu Note 1
CSIE33000 Network Programming Lecture 11 JDBC
JDBC Drivers
JDBC is a general access method. It can not
directly process internal format of databases
of different vendors
vendors.
A driver is needed to allow JDBC to
communicate with vendor-specific API.
Drivers for different databases are either
provided by the vendors or by third parties
parties.
Visit
http://servlet.java.sun.com/products/jdbc/dri
vers for more information.
CSIE33000 Network Programming JDBC 3
Shiow-yang Wu Note 2
CSIE33000 Network Programming Lecture 11 JDBC
Shiow-yang Wu Note 3
CSIE33000 Network Programming Lecture 11 JDBC
Shiow-yang Wu Note 4
CSIE33000 Network Programming Lecture 11 JDBC
Sample Database
We will assume the existence of an MS
Access database called Finances.mdb
A single
l table
bl called
ll d Accounts
Field Name MS Access Type Java Type
acctNum Number int
surname Text String
firstNames Text String
balance Currency float
Assume the DSN is Finances
CSIE33000 Network Programming JDBC 10
Shiow-yang Wu Note 5
CSIE33000 Network Programming Lecture 11 JDBC
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
2. Establish a Connection to
the Database
Call getConnection of class DriverManager which
returns a ref to a Connection object.
Takes a URL-style DB address, a username, a
password. For local database
Connection link =
DriverManager.getConnection(“jdbc:odbc:Finances”, “”,
“”);
For remote database
Connection link =
DriverManager.getConnection(“jdbc:odbc://AnyServer.S
omethingElse.com/Finances”, “”, “”);
CSIE33000 Network Programming JDBC 12
Shiow-yang Wu Note 6
CSIE33000 Network Programming Lecture 11 JDBC
4. Run a Query/Update
Statement class has methods executeQuery
and executeUpdate.
executeQuery returns a ResultSet
l
executeUpdate returns an integer indicating
the number of rows being affected
It is common to store the SQL query in a
String and then invoke executeQuery.
executeQuery
We will give a few query examples (next
slide).
Shiow-yang Wu Note 7
CSIE33000 Network Programming Lecture 11 JDBC
Query Examples
1. String selectAll = “SELECT * FROM Accounts”;
ResultSet results = statement.executeQuery(selectAll);
2
2. String selectFields = “SELECT
SELECT accNum,
accNum balance FROM
Accounts”;
ResultSet results =
statement.executeQuery(selectFields);
3. String selectRange = “SELECT * FROM Accounts”
+ “ WHERE balance >= 0”
+ “ AND balance <= 1000”
+ “ ORDER BY balance DESC”;
ResultSet results =
statement.executeQuery(selectRange);
CSIE33000 Network Programming JDBC 15
5. Manipulate/Display/Check
Result(s)
The ResultSet object contains the database
rows that satisfy the query.
ResultSet contains a very large number of
methods for manipulating these rows.
We will use the next method and the getXXX
methods in a while loop
A getXXX method can have a columnName or
a columnIndex as argument.
Index is within the ResultSet row!!
CSIE33000 Network Programming JDBC 16
Shiow-yang Wu Note 8
CSIE33000 Network Programming Lecture 11 JDBC
Using ColumnIndex
String select = "SELECT * FROM Accounts";
ResultSet results = statement.executeQuery(select);
while (results.next())
(results next())
{
System.out.println("Account no.“ + results.getInt(1));
System.out.println("Account holder: "
+ results.getString(3) + " "
+ results.getString(2));
results getString(2));
System.out.println("Balance: “ + results.getFloat(4));
System.out.println ();
}
CSIE33000 Network Programming JDBC 17
Using ColulmnName
...
while (results.next())
{
System.out.println("Account no.“ +
results.getInt(“acctNum”));
System.out.println("Account holder: "
+ results.getString(“firstNames”) + " "
+ results.getString(“surName”));
System out println("Balance:
System.out.println( Balance: “
+ results.getFloat(“balance”));
System.out.println ();
}
Shiow-yang Wu Note 9
CSIE33000 Network Programming Lecture 11 JDBC
6. Repeat 4, 5 as required
The Statement reference can be reused to
execute other queries or updates.
For eachh operation, simply
l repeat step 4 and
d
step 5
Repeat as many times as required by the
applications
Shiow-yang Wu Note 10
CSIE33000 Network Programming Lecture 11 JDBC
JDBCSelect.java (1)
import java.sql.*;
JDBCSelect.java (2)
catch(SQLException sqlEx)
{
System.out.println("* Cannot connect to database! *");
System.exit(1);
}
try {
statement = link.createStatement(); //Step 3.
String select = “SELECT * FROM Accounts”; //Step 4.
results = statement.executeQuery(select); //Step 4.
}
catch(SQLException
t h(SQLE ti sqlEx)
lE )
{
System.out.println("* Cannot execute query! *");
sqlEx.printStackTrace();
System.exit(1);
}
CSIE33000 Network Programming JDBC 22
Shiow-yang Wu Note 11
CSIE33000 Network Programming Lecture 11 JDBC
JDBCSelect.java (3)
try {
System.out.println();
JDBCSelect.java (4)
//No further queries, no Step 6.
try {
link close(); //Step 7
link.close(); 7.
}
catch(SQLException sqlEx)
{
System.out.println(
"* Unable to disconnect! *");
sqlEx.printStackTrace();
}
}
}
CSIE33000 Network Programming JDBC 24
Shiow-yang Wu Note 12
CSIE33000 Network Programming Lecture 11 JDBC
JDBCSelect Execution
Database Update
SQL statements for modifying databases: INSERT, DELETE, UPDATE
For JDBC, we need to use executeUpdate method.
Examples:
S i insert
String i = "INSERT INTO Accounts”
A ”
+ " VALUES (123456, 'Smith', 'John James', 752.85)";
int result = statement.executeUpdate(insert);
Shiow-yang Wu Note 13
CSIE33000 Network Programming Lecture 11 JDBC
JDBCChange.java (1)
import java.sql.*;
//Step 2...
link = DriverManager.getConnection("jdbc:odbc:Finances", "", "");
}
Shiow-yang Wu Note 14
CSIE33000 Network Programming Lecture 11 JDBC
JDBCChange.java (2)
catch(ClassNotFoundException cnfEx) {
System.out.println ("* Unable to load driver! *");
System.exit(1);
}
//For any of a number of reasons, it may not be
//possible to establish a connection...
catch(SQLException sqlEx) {
System.out.println ("* Cannot connect to database! *");
System.exit(1);
}
tryy {
//Step 3...
statement = link.createStatement();
JDBCChange.java (3)
//Start of step 6...
String insert = "INSERT INTO Accounts"
+ " VALUES (112233, 'Smith‘, John James', 752.85)";
int result = statement.executeUpdate(insert);
if (result == 0)
System.out.println("\nUnable to insert record!");
Shiow-yang Wu Note 15
CSIE33000 Network Programming Lecture 11 JDBC
JDBCChange.java (4)
if (result == 0)
System.out.println("\nUnable to delete record!");
//Step 7...
link.close();
}
catch(SQLException sqlEx)
{
System.out.println("* SQL or connection error! *");
sqlEx.printStackTrace();
System.exit(1);
}
}
JDBCChange.java (5)
public static void displayTable() throws SQLException
{
String select = "SELECT * FROM Accounts";
results = statement.executeQuery(select);
statement executeQuery(select);
System.out.println();
while (results.next())
{
System.out.println("Account no. “ + results.getInt(1));
System.out.println("Account
System.out.println( Account holder: “ + results.getString(3) + " "
+ results.getString(2));
Shiow-yang Wu Note 16
CSIE33000 Network Programming Lecture 11 JDBC
JDBCChange Execution
Transactions
A transaction is one or more SQL statements that are
grouped together as a single entity.
Transaction execution must satisfyy the All-or-None
property.
In SQL, this is done by COMMIT and ROLLBACK
statements.
In JDBC, they are the commit and rollback methods of the
Connection.
Th commit
The it method
th d is
i used
d att the
th end
d off a transaction
t ti tto
commit/finalize the DB update.
The rollback method is used to restore the DB to the prior
consistent state.
Shiow-yang Wu Note 17
CSIE33000 Network Programming Lecture 11 JDBC
Shiow-yang Wu Note 18
CSIE33000 Network Programming Lecture 11 JDBC
Shiow-yang Wu Note 19
CSIE33000 Network Programming Lecture 11 JDBC
JDBCMetaData.java (1)
import java.sql.*;
//Step 2...
link = DriverManager.getConnection(
"jdbc:odbc:Finances", "", "");
}
JDBCMetaData.java (2)
catch(ClassNotFoundException cnfEx) {
System.out.println ("* Unable to load driver! *");
System.exit(1);
}
catch(SQLException sqlEx) {
System.out.println("* Cannot connect to database! *");
System.exit(1);
}
try {
//Step 3...
statement = link.createStatement();
link createStatement();
Shiow-yang Wu Note 20
CSIE33000 Network Programming Lecture 11 JDBC
JDBCMetaData.java (3)
//Start of step 5...
ResultSetMetaData metaData = results.getMetaData();
int numFields = metaData.getColumnCount();
boolean found = results.next();
if (!found) {
System.out.println("\nNot found!");
link.close();
return;
}
JDBCMetaData.java (4)
int colType = metaData.getColumnType(i);
System.out.print("Value: ");
switch (colType)
{
case Types.INTEGER:
System.out.println(results.getInt(i));
break;
case Types.VARCHAR:
System.out.println(results.getString(i));
break;
case Types.NUMERIC:
System out printf("%
System.out.printf( %.2f2f %n%n
%n%n",
results.getFloat(i));
break;
default: System.out.println("Unknown");
}
}
Shiow-yang Wu Note 21
CSIE33000 Network Programming Lecture 11 JDBC
JDBCMetaData.java (5)
//(No further queries, so no Step 6!)
// p 7...
//Step
link.close();
}
catch(SQLException sqlEx)
{
System.out.println("* SQL or connection error! *");
sqlEx.printStackTrace();
q p a a ();
System.exit(1);
}
}
}
CSIE33000 Network Programming JDBC 43
JDBCMetaData Execution
Shiow-yang Wu Note 22
CSIE33000 Network Programming Lecture 11 JDBC
JDBCGUI.java (1)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import
p java.sql.*;
j q ;
import java.util.*;
Shiow-yang Wu Note 23
CSIE33000 Network Programming Lecture 11 JDBC
JDBCGUI.java (2)
public static void main(String[] args) {
JDBCGUI frame = new JDBCGUI();
frame.setSize(400,200);
frame.setVisible(true);
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent winEvent) {
try {
link.close();
System.exit(0);
}
catch(SQLException sqlEx) {
System.out.println("* Error on closing connection! *");
}
}
}
);
}
CSIE33000 Network Programming JDBC 47
JDBCGUI.java (3)
public JDBCGUI() {
setTitle("Accounts Data");
try {
Class forName("sun
Class.forName( sun.jdbc.odbc.JdbcOdbcDriver
jdbc odbc JdbcOdbcDriver");
);
link = DriverManager.getConnection(
"jdbc:odbc:Finances","","");
statement = link.createStatement();
results = statement.executeQuery(
"SELECT * FROM Accounts");
Shiow-yang Wu Note 24
CSIE33000 Network Programming Lecture 11 JDBC
JDBCGUI.java (4)
while (results.next()) {
row = new Vector<Object>();//Heterogeneous collection.
row.add(results.getInt(1));
row.add(results.getString(2));
row.add(results.getString(3));
row.add(results.getFloat(4));
rows.add(row);
}
table = new JTable(rows,heads);
scroller = new JScrollPane(table);
add(scroller, BorderLayout.CENTER);
}
catch(ClassNotFoundException cnfEx)
{
System.out.println("* Unable to load driver! *");
System.exit(1);
}
JDBCGUI.java (5)
catch(SQLException sqlEx)
{
System.out.println("* SQL error! *");
System.exit(1);
}
}
}
Shiow-yang Wu Note 25
CSIE33000 Network Programming Lecture 11 JDBC
JDBCGUI Execution
Shiow-yang Wu Note 26
CSIE33000 Network Programming Lecture 11 JDBC
Relative/Absolute Moving
Method relative takes a signed arg and
moves forwards/backwards the specified
number of rows
rows.
results.relative(-3); //Move back 3 rows.
Method absolute takes a signed arg and
moves to the specified absolute position,
counting either from the start (positive arg)
or the end (negative arg).
results.absolute(3);
//Move to row 3 (from the start)
CSIE33000 Network Programming JDBC 53
Scrollable ResultSet
Must create a scrollable ResultSet first.
Done by the Connection method
c eateStatement with
createStatement ith two
t o args.
a gs
Statement createStatement(
int <resultSetType>,
int <resultSetConcurrency>)
Three possible values for resultSetType:
TYPE_FORWARD_ONLY
TYPE_SCROLL_INSENSITIVE
TYPE_SCROLL_SENSITIVE
CSIE33000 Network Programming JDBC 54
Shiow-yang Wu Note 27
CSIE33000 Network Programming Lecture 11 JDBC
Scrollable ResultSet
Two possible values for the
resultSetConcurrency arg:
CONCUR_READ_ONLY
CONCUR READ ONLY
CONCUR_UPDATABLE
The first value means that we cannot make
changes to the ResultSet rows.
The second one allows changes to be made
(and to be reflected in the database)
(more on updatable later)
JDBCScrollableSelect.java
import java.sql.*;
Shiow-yang Wu Note 28
CSIE33000 Network Programming Lecture 11 JDBC
JDBCScrollableSelect.java
catch(SQLException sqlEx) {
System.out.println("* Cannot connect to database! *");
System.exit(1);
}
try {
statement =
link.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
results = statement.executeQuery("SELECT * FROM Accounts");
}
catch(SQLException sqlEx) {
System.out.println("* Cannot execute query! *");
sqlEx.printStackTrace();
System.exit(1);
}
JDBCScrollableSelect.java
try {
while (results.next())
showRow();
}
catch(SQLException sqlEx) {
System.out.println("* Error retrieving data! *");
sqlEx.printStackTrace();
System.exit(1);
}
try {
while (results.previous())
showRow();
}
Shiow-yang Wu Note 29
CSIE33000 Network Programming Lecture 11 JDBC
JDBCScrollableSelect.java
catch(SQLException sqlEx) {
System.out.println("* Error retrieving data! *");
q p ();
sqlEx.printStackTrace();
System.exit(1);
}
try {
link.close();
}
catch(SQLException sqlEx) {
System.out.println("* Unable to disconnect! *");
sqlEx.printStackTrace();
}
}
JDBCScrollableSelect.java
static void showRow() throws SQLException
{
System.out.println();
System.out.println("Account no. "
+ results.getInt(1));
System.out.println("Account holder: "
+ results.getString(3)
+ " " + results.getString(2));
S t
System.out.printf("Balance:
t i tf("B l %
%.2f
2f %
%n%n",
% "
results.getFloat(4));
}
}
CSIE33000 Network Programming JDBC 60
Shiow-yang Wu Note 30
CSIE33000 Network Programming Lecture 11 JDBC
JDBCScrollableSelect Execution
Shiow-yang Wu Note 31
CSIE33000 Network Programming Lecture 11 JDBC
Shiow-yang Wu Note 32
CSIE33000 Network Programming Lecture 11 JDBC
Shiow-yang Wu Note 33
CSIE33000 Network Programming Lecture 11 JDBC
JDBC2Mods.java (1)
import java.sql.*;
//Step 2...
link = DriverManager.getConnection(
"jdbc:odbc:Finances", "", "");
}
JDBC2Mods.java (2)
catch(ClassNotFoundException cnfEx) {
System.out.println ("* Unable to load driver! *");
System.exit(1);
}
//For any of a number of reasons, it may not be
//possible to establish a connection...
catch(SQLException sqlEx) {
System.out.println("* Cannot connect to database! *");
System.exit(1);
}
try {
//Step 3...
statement = link.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
CSIE33000 Network Programming JDBC 68
Shiow-yang Wu Note 34
CSIE33000 Network Programming Lecture 11 JDBC
JDBC2Mods.java (3)
System.out.println("\nInitial contents of table:\n");
//Steps 4 and 5...
displayTable();
JDBC2Mods.java (4)
//Finally, the deletion...
results.absolute(3); //Move to row 3.
results.deleteRow();
//Step 7...
link.close();
}
catch(SQLException sqlEx)
{
System.out.println("* SQL or connection error! *");
sqlEx.printStackTrace();
System.exit(1);
}
}
Shiow-yang Wu Note 35
CSIE33000 Network Programming Lecture 11 JDBC
JDBC2Mods.java (5)
public static void displayTable() throws SQLException {
String select = "SELECT * FROM Accounts";
results = statement.executeQuery(select);
statement executeQuery(select);
System.out.println();
while (results.next()) {
System.out.println("Account no. “ + results.getInt(1));
System.out.println("Account holder: “ + results.getString(3)
+ " " + results.getString(2));
g g( ));
System.out.printf("Balance: %.2f %n%n",
results.getFloat(4));
}
}
}
JDBC2Mods Execution
Shiow-yang Wu Note 36