0% found this document useful (0 votes)
123 views36 pages

Java Database Connectivity (JDBC) : CSIE33000 NT KP I Ij Network Programming in Java

This document provides an overview of Java Database Connectivity (JDBC) and how to connect a Java program to a relational database. It discusses JDBC drivers, the JDBC-ODBC bridge driver, SQL and JDBC versions, and the basic 7 steps to access a database: 1) load the driver, 2) establish a connection, 3) create a Statement object, 4) run a query/update, 5) manipulate/display results, 6) repeat as needed, and 7) close the connection. It also provides an example of connecting to a sample MS Access database table called Accounts using the JDBC-ODBC driver.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views36 pages

Java Database Connectivity (JDBC) : CSIE33000 NT KP I Ij Network Programming in Java

This document provides an overview of Java Database Connectivity (JDBC) and how to connect a Java program to a relational database. It discusses JDBC drivers, the JDBC-ODBC bridge driver, SQL and JDBC versions, and the basic 7 steps to access a database: 1) load the driver, 2) establish a connection, 3) create a Statement object, 4) run a query/update, 5) manipulate/display results, 6) repeat as needed, and 7) close the connection. It also provides an example of connecting to a sample MS Access database table called Accounts using the JDBC-ODBC driver.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

CSIE33000 Network Programming Lecture 11 JDBC

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

CSIE33000 Network Programming JDBC 2

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

JDBC-ODBC Bridge Driver


„ Open Database Connectivity (ODBC) is the
Microsoft’s solution for access databases.
„ ODBC drivers
d are available
l bl for
f most off the
h
major databases.
„ In such case, the JDBC-ODBC bridge driver
(in package sun.jdbc.odbc) is provided to
convert JDBC protocol into ODBC which
allows Java program to access databases for
which there are ODBC drivers.
„ Extra conversion may lead to long delays.
CSIE33000 Network Programming JDBC 4

Shiow-yang Wu Note 2
CSIE33000 Network Programming Lecture 11 JDBC

SQL and JDBC Versions


„ SQL is the de facto standard for accessing
relational databases.
„ The
h core JDBC API is called
ll d java.sqll
„ JDK1.1 JDBC 1.0
„ JDK1.2 (J2SE 1.2) JDBC 2.0
„ J2SE 1.2.2, 1.3 JDBC 2.1
„ JDBC 2.0 Extension Package API (javax.sql)
„ J2SE 1.4 JDBC 3.0
„ JDBC 3.0 includes: java.sql and javax.sql
CSIE33000 Network Programming JDBC 5

Drivers and DB to Use


„ There are still many JDBC 1 drivers.
„ The most commonly used version is JDBC 2.
„ JDBC 3 drivers are increasing.
„ We will start from JDBC 1 and then to 2, 3
„ We will use MS Access database for the
purposes of illustration.
„ The built in JDBC-ODBC driver in J2SE can be
employed.
„ We need to build an ODBC Data Source.
CSIE33000 Network Programming JDBC 6

Shiow-yang Wu Note 3
CSIE33000 Network Programming Lecture 11 JDBC

Creating an ODBC Data Source


„ Must register the database as an ODBC Data
Source first.
„ Once registered,
registered the database can be referred
to by its Data Source Name (DSN).
„ Create an ODBC Data Source:
1. Start(開始) -> Cntrol Panel(控制台)
2. Double-click Administrative Tools (系統管理工
具)
3. Double-click Data Sources (ODBC) 資料來源
(ODBC)
4. Select the User DSN tab (使用者資料來源)
CSIE33000 Network Programming JDBC 7

Register ODBC Data Source


5. Click Add… to display the Create New Data
Source window (新增 -> 建立新資料來源)
6. Select Mic
Microsoft
osoft Access D
Driver
i e (*
(*.mdb)
mdb) and
click Finish (完成)
7. Click Select(選取) and locate the database
8. Supply a meaningful name for the data source
(
(資料來源名稱) )
9. To specify username and password, select
Advanced Options (進階) (not necessary)
10. Click OK (確定) to finish registration.
CSIE33000 Network Programming JDBC 8

Shiow-yang Wu Note 4
CSIE33000 Network Programming Lecture 11 JDBC

7 Steps to Database Access


1. Load the database driver
2. Establish a connection to the database
3. Create a Statement object using the connection
and store a reference to it
4. Use the Statement reference to run a query or
update and accept the result(s)
5. Manipulate the display the results (query) or
check/show number of rows affected (update)
6. Repeat 4, 5 as many times as required
7. Close the connection.
CSIE33000 Network Programming JDBC 9

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

1. Load the Database Driver


„ This is done via static method forName of
the class Class

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

CSIE33000 Network Programming JDBC 11

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

3. Create a Statement obj


„ Done by calling the createStatement method
of the Connection object
Statement statement = link.createStatement();
l k ()

CSIE33000 Network Programming JDBC 13

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).

CSIE33000 Network Programming JDBC 14

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 ();
}

CSIE33000 Network Programming JDBC 18

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

CSIE33000 Network Programming JDBC 19

7. Close the Connection


„ Close the Connection object
link.close();
„ Close the Statement object
statement.close();

„ SQLException must be catched for any SQL


statement
„ ClassNotFoundException is generated when
the database driver cannot be found
CSIE33000 Network Programming JDBC 20

Shiow-yang Wu Note 10
CSIE33000 Network Programming Lecture 11 JDBC

JDBCSelect.java (1)
import java.sql.*;

public class JDBCSelect {


private
i t static
t ti Connection
C ti link;
li k
private static Statement statement;
private static ResultSet results;

public static void main(String[] args) {


try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Step 1.
link = DriverManager.getConnection(
DriverManager getConnection("jdbc:odbc:Finances"
jdbc:odbc:Finances ,"","");
); //Step 2
2.
}
catch(ClassNotFoundException cnfEx) {
System.out.println("* Unable to load driver! *");
System.exit(1);
}

CSIE33000 Network Programming JDBC 21

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();

while (results.next()) { //Step 5.


System.out.println("Account no. “ + results.getInt(1));
System.out.println("Account holder: "
+ results.getString(3) + " "+ results.getString(2));
System.out.printf("Balance: %.2f %n%n", results.getFloat(4));
}
}
catch(SQLException sqlEx) {
System.out.println("* Error retrieving data! *");
sqlEx.printStackTrace();
System.exit(1);
}

CSIE33000 Network Programming JDBC 23

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

CSIE33000 Network Programming Java I/O 25

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);

String change = "UPDATE Accounts"


+ " SET surname = 'Bloggs', firstNames = 'Fred Joseph'"
+ " WHERE acctNum = 123456
123456";;
statement.executeUpdate(change);

String remove = "DELETE FROM Accounts WHERE balance < 100";


result = statement.executeUpdate(remove);

CSIE33000 Network Programming JDBC 26

Shiow-yang Wu Note 13
CSIE33000 Network Programming Lecture 11 JDBC

Checking the Result


„ In general, the return value is used to check
whether the update has been carried out
successfully.
successfully
int result = statement.executeUpdate(insert);
if (result==0)
System.out.println("* Insertion failed! *");

CSIE33000 Network Programming JDBC 27

JDBCChange.java (1)
import java.sql.*;

public class JDBCChange {


static Connection link;
static
t ti St
Statement
t t statement;
t t t
static ResultSet results;
//Alternatively, the above 3 variables may
//be declared non-static within main, but
//must then be initialised explicitly to null.

public static void main(String[] args) {


try {
//Step 1...
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//Step 2...
link = DriverManager.getConnection("jdbc:odbc:Finances", "", "");
}

CSIE33000 Network Programming JDBC 28

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();

System.out.println("\nInitial contents of table:");


//Steps 4 and 5...
displayTable();

CSIE33000 Network Programming JDBC 29

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!");

String change = "UPDATE Accounts"


+ " SET surname = 'Bloggs‘, firstNames = 'Fred Joseph'"
+ " WHERE acctNum = 123456";
result = statement.executeUpdate(change);
if (result == 0)
System.out.println("\nUnable to update record!");

String remove = "DELETE FROM Accounts"


+ " WHERE balance < 100“;
result = statement.executeUpdate(remove);

CSIE33000 Network Programming JDBC 30

Shiow-yang Wu Note 15
CSIE33000 Network Programming Lecture 11 JDBC

JDBCChange.java (4)
if (result == 0)
System.out.println("\nUnable to delete record!");

System.out.println("\nNew contents of table:");


displayTable();
//End of step 6.

//Step 7...
link.close();
}
catch(SQLException sqlEx)
{
System.out.println("* SQL or connection error! *");
sqlEx.printStackTrace();
System.exit(1);
}
}

CSIE33000 Network Programming JDBC 31

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));

System.out.printf("Balance: %.2f %n%n", results.getFloat(4));


}
}
}

CSIE33000 Network Programming JDBC 32

Shiow-yang Wu Note 16
CSIE33000 Network Programming Lecture 11 JDBC

JDBCChange Execution

CSIE33000 Network Programming Java I/O 33

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.

CSIE33000 Network Programming JDBC 34

Shiow-yang Wu Note 17
CSIE33000 Network Programming Lecture 11 JDBC

Transactions with JDBC


„ By default, JDBC automatically commits each SQL
statement.
„ Use setAutoCommit(false) of the Connection to switch off
the auto commit
commit.
link.setAutoCommit(false);
try {
//Assumes 3 SQL update strings:update1, update2 and update3.
statement.executeUpdate(update1);
statement.executeUpdate(update2);
statement.executeUpdate(update3);
link commit();
link.commit();
}
catch(SQLException sqlEx) {
link.rollback();
System.out.println("* SQL error! Changes aborted... *");
}
CSIE33000 Network Programming JDBC 35

Meta Data (1)


„ Meta data is “data about data”.
„ Two categories of meta data for JDBC API:
„ Data about
abo t ResultSet
Res ltSet objects ((rows,
o s col
columns,
mns …))
„ Data about the DB as a whole.
„ Use the getMetaData method of ResultSet to
obtain a ResultSetMetaData object to access:
„ No. of fields/columns
„ Field names
„ Data type of a field
„ Max width of a field
„ The table to which a field belongs
CSIE33000 Network Programming JDBC 36

Shiow-yang Wu Note 18
CSIE33000 Network Programming Lecture 11 JDBC

Meta Data (2)


„ Use the getMetaData method of Connection
to obtain a DatabaseMetaData object.
However it is rarely used
However, used.
„ All SQL types is represented in class
java.sql.Types as 28 named static int const.
„ DATE NUMERIC
„ DECIMAL REAL
„ DOUBLE VARCHAR
„ FLOAT …
„ INTEGER
CSIE33000 Network Programming JDBC 37

Meta Data (3)


„ Methods of ResultSetMetaData to access
properties of database fields:
„ iintt getColumnCount()
tC l C t()
„ String getColumnName(<colNumber>)
„ int getColumnType(<colNumber>)
(returns an int const of the SQL types, last slide)
„ String getColumnTypeName(
getColumnTypeName(<colNumber>)
colNumber )
(returns the DB-specific type name in String)
„ String getTableName(<colNumber>)

CSIE33000 Network Programming JDBC 38

Shiow-yang Wu Note 19
CSIE33000 Network Programming Lecture 11 JDBC

JDBCMetaData.java (1)
import java.sql.*;

public class JDBCMetaData {


static Connection link;
static Statement statement;
static ResultSet results;

public static void main(String[] args) {


try {
//Step 1...
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//Step 2...
link = DriverManager.getConnection(
"jdbc:odbc:Finances", "", "");
}

CSIE33000 Network Programming JDBC 39

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();

String select = "SELECT * FROM Accounts"


+ " WHERE acctNum = 123456";
//Step 4...
results = statement.executeQuery(select);

CSIE33000 Network Programming JDBC 40

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;
}

for (int i=1; i<=numFields; i++) { //Count start at 1 !!


System.out.println("\nField name: "
+ metaData.getColumnName(i));

System.out.println("Field type: "


+ metaData.getColumnTypeName(i));

CSIE33000 Network Programming JDBC 41

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");
}
}

CSIE33000 Network Programming JDBC 42

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

CSIE33000 Network Programming Java I/O 44

Shiow-yang Wu Note 22
CSIE33000 Network Programming Lecture 11 JDBC

Using GUI to Access DB


„ We want our DB access to go through GUI.
„ The DB table can be displayed using the Swing
class JTable which displays data in a table
format with column headings.
„ One of the commonly used constructor:
Jtable(Vector <rowData>, Vector <colNames>)
„ 1st arg holds the rows to be displayed (as a
Vector of Vectors of type
Vector<Vector<Object>>)
„ 2nd arg holds the names of the column headings
(of type Vector<String>).
CSIE33000 Network Programming JDBC 45

JDBCGUI.java (1)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import
p java.sql.*;
j q ;
import java.util.*;

public class JDBCGUI extends JFrame


{
static private Connection link;
private Statement statement;
private ResultSet results;
private JTable table;
private
i t JScrollPane
JS llP scroller;
ll
private final String[] heading =
{"Account No.","Surname","First Names","Balance"};
private Vector<String> heads;
private Vector<Object> row;
private Vector<Vector<Object>> rows;

CSIE33000 Network Programming JDBC 46

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");

heads = new Vector<String>();


for (int i=0; i<heading.length; i++) {
heads.add(heading[i]);
}

rows = new Vector<Vector<Object>>();

CSIE33000 Network Programming JDBC 48

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);
}

CSIE33000 Network Programming JDBC 49

JDBCGUI.java (5)
catch(SQLException sqlEx)
{
System.out.println("* SQL error! *");
System.exit(1);
}
}
}

CSIE33000 Network Programming JDBC 50

Shiow-yang Wu Note 25
CSIE33000 Network Programming Lecture 11 JDBC

JDBCGUI Execution

CSIE33000 Network Programming Java I/O 51

Scrollable ResultSets (JDBC 2)


„ In JDBC 1, the only method for moving through a
ResultSet is next.
„ With JDBC 2 2, more methods of ResultSet are
provided:
„ boolean first()
„ boolean last()
„ boolean previous()
„ boolean relative(int
( <rows>))
„ boolean absolute(int <rows>)
„ The return value denotes if there is data at the
specified position.

CSIE33000 Network Programming JDBC 52

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)

CSIE33000 Network Programming JDBC 55

JDBCScrollableSelect.java
import java.sql.*;

public class JDBCScrollableSelect {


static private Connection link;
static private Statement statement;
static private ResultSet results;

public static void main(String[] args) {


try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
link = DriverManager.getConnection(
"jdbc:odbc:Finances"
jdbc:odbc:Finances ,"","");
);
}
catch(ClassNotFoundException cnfEx) {
System.out.println("* Unable to load driver! *");
System.exit(1);
}

CSIE33000 Network Programming JDBC 56

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);
}

CSIE33000 Network Programming JDBC 57

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();
}

CSIE33000 Network Programming JDBC 58

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();
}
}

CSIE33000 Network Programming JDBC 59

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

CSIE33000 Network Programming JDBC 61

Modifying DB with Java


„ JDBC 2 allows the modification of ResultSet
rows directly via Java methods and to have
those changes reflected in the database !
„ Must use ResultSet.CONCUR_UPDATABLE in
the createStatement.
Statement statement = link.createStatement(
ResultSet TYPE SCROLL SENSITIVE
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

CSIE33000 Network Programming JDBC 62

Shiow-yang Wu Note 31
CSIE33000 Network Programming Lecture 11 JDBC

Updating DB with Java


„ The updates are done through the set of
updateXXX methods, such as updateString,
updateInt Each method takes two args:
updateInt.
„ A string specifying the field name.
„ A value of proper type to be assigned to the field
„ Three steps to update:
„ Position the ResultSet cursor at the required row
„ Call the appropriate updateXXX method(s)
„ Call method updateRow()

CSIE33000 Network Programming JDBC 63

Updating DB with Java


„ Example of updating DB
results.absolute(2);//Move to row 2
results.updateFloat("balance", 42.55f);
results.updateRow();

CSIE33000 Network Programming JDBC 64

Shiow-yang Wu Note 32
CSIE33000 Network Programming Lecture 11 JDBC

Insertion using Java


„ Three steps to insert a new row:
„ Call method moveToInsertRow
„ Call proper updateXXX method for each field of the row
„ Call method insertRow()
„ Example:
results.moveToInsertRow();
results.updateInt("acctNum", 999999);
results.updateString("surname", "Harrison");
results.updateString("firstNames", "Christine Dawn");
results.updateFloat("balance", 2500f);
results.insertRow();
CSIE33000 Network Programming JDBC 65

Deleting Rows in Java


„ Two steps to delete a row:
„ Move to the appropriate row
„ Callll method
h d deleteRow()
d l ()
„ Example
results.absolute(3); //Move to row 3.
results.deleteRow();

„ Note that different JDBC drivers may handle


deletions differently.
CSIE33000 Network Programming JDBC 66

Shiow-yang Wu Note 33
CSIE33000 Network Programming Lecture 11 JDBC

JDBC2Mods.java (1)
import java.sql.*;

public class JDBC2Mods {


static private Connection link;
static private Statement statement;
static private ResultSet results;

public static void main(String[] args) {


try {
//Step 1...
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//Step 2...
link = DriverManager.getConnection(
"jdbc:odbc:Finances", "", "");
}

CSIE33000 Network Programming JDBC 67

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();

//Start of step 6...

//First the update...


results.absolute(2);//Move to row 2 of ResultSet.
results.updateFloat("balance", 42.55f);
results.updateRow();

//Now the insertion...


results.moveToInsertRow();
lt T I tR ()
results.updateInt("acctNum", 999999);
results.updateString("surname", "Harrison");
results.updateString("firstNames", "Christine Dawn");
results.updateFloat("balance", 2500f);
results.insertRow();

CSIE33000 Network Programming JDBC 69

JDBC2Mods.java (4)
//Finally, the deletion...
results.absolute(3); //Move to row 3.
results.deleteRow();

System.out.println("\nNew contents of table:\n");


displayTable();
//End of step 6.

//Step 7...
link.close();
}
catch(SQLException sqlEx)
{
System.out.println("* SQL or connection error! *");
sqlEx.printStackTrace();
System.exit(1);
}
}

CSIE33000 Network Programming JDBC 70

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));
}
}
}

CSIE33000 Network Programming JDBC 71

JDBC2Mods Execution

CSIE33000 Network Programming JDBC 72

Shiow-yang Wu Note 36

You might also like