You are on page 1of 55

TRNG I HC CNG NGH THNG TIN

KHOA CNG NGH PHN MM

LP TRNH JDBC
(JAVA DATABASE CONNECTIVITY)

NI DUNG
Khi nim c bn
Kin trc JDBC & JDBC APIs
Cc bc lm vic vi Database dng JDBC
Mt s lp v phng thc c bn trong JDBC API
Cc loi JDBC Drivers
V d minh ha

Gii thiu v JDBC


JDBC (Java DataBase Connectivity) l mt th vic

chun dng truy xut cc c s d liu nh MS


Acess, SQL Server, Oracle, trong cc ng dng
Java bng ngn ng truy vn SQL.
Cc hm truy xut c s d liu vi JDBC nm trong
gi java.sql.*
CSDL

JDBC

JDBC
JDBC
3

CSDL

Ti sao cn JDBC?
JDBC gip cc Java Developers to nn cc ng dng

truy xut c s d liu m khng cn phi hc v s


dng cc APIs do cc cng ty sn xut phn mm
khc nhau bn th ba cung cp. JDBC m bo rng
bn s c th pht trin nn cc ng dng truy cp
c s d liu c kh nng truy cp n cc RDBMS
khc nhau bng cch s dng cc JDBC driver khc
nhau.

Kin trc JDBC

Cc khi nim c bn
JDBC API: l mt API hon ton da trn Java.
JDBC DriverManager: l trnh qun l JDBC
giao tip trc tip vi cc trnh iu khin c
s d liu c th - giao tip thc s vi c s
d liu.
Cc RDBMS hay cc nh sn xut phn mm
th 3 pht trin cc drivers cho java u phi
tun th c t JDBC ca SUN.
Cc java developers dng cc JDBC drivers
pht trin cc ng dng c truy cp, thao
tc CSDL.

JDBC Dirvers
L mt chng trnh my tnh gip truy cp n cc

h DBMS khc nhau dng k thut JDBC


Do cc hng xy dng DBMS hoc mt n v th 3
khc cung cp.
http://industry.java.sun.com/products/jdbc/drivers.

Cc loi JDBC Dirvers


JDBC-ODBC Bridge plus ODBC Driver
A native API partly Java technology-enabled driver
Pure Java Driver for Database Middleware
Direct-to-Database Pure Java Driver

Cc loi JDBC Dirvers


Type 1: JDBC-ODBC Bridge
Java
Java
Applications
Applications

JDBC Driver Type 1


JDBC Driver Type 1

JDBC-ODBC

nhim

cng vic truy cp d liu


cho ODBC API. Chng l
trnh iu khin chm nht
trong s cn li.

JDBC-ODBC Library
JDBC-ODBC Library

Phng thc truy xut d liu i


hi trnh iu khin ODBC c ci

ODBC
ODBC
Driver
Driver

Database
Database

t trn my tnh client.

Cc loi JDBC Dirvers


Type 2: Java to Native API
Java
Java
Applications
Applications

JDBC Driver Type 2


JDBC Driver Type 2
Database
Database
Library
Library

Database
Database

Dng Java Native API (JNI)


gi n cc th vin API
ca database.
Khi s chuyn i ny t trn
my client, mt s m nh phn
phi c ci t trn my tnh
client.

Cc loi JDBC Dirvers


Type 3: Java to Network Protocol Or All- Java Driver
Java
Java
Applications
Applications

Dng Network protocol giao

tip

vi

JDBC

middleware

trn

server.
JDBC Driver Type 3
JDBC Driver Type 3

Chuyn i cc li gi JDBC thnh


giao thc mng c lp vi bt k giao

Network protocol

JDBC Middleware
JDBC Middleware
(java)
(java)

thc DBMS c th. Sau , mt phn


mm trung gian (middleware) chy trn
my server chuyn i giao thc mng
thnh giao thc DBMS c th.
S chuyn ny t pha server m

Database
Database

khng i hi ci t trn my tnh


client.

Cc loi JDBC Dirvers


Type 4: Java to Database Protocol
Java
Java
Applications
Applications

Drivers thun java v

JDBC Driver Type 4


JDBC Driver Type 4

protocol giao tip trc

hin

thc/dng

database

tip vi CSDL. Thng l


nhng JDBC drivers nhanh
Database
Database

nht.
Chuyn li gi JDBC thnh cc
li gi giao thc DBMS c th.

Cch np Database Driver?


Driver c ci t trong JAR file.
JAR phi c khai bo trong classpath:

Thm jar file to vo IDE project

Thm JAR file vo CLASSPATH


CLASSPATH = /my/path/mysql-connector.jar;.

Thm JAR s dng Java command line:


java -cp /my/path/mysql-connector.jar ...

t JAR file vo JRE/lib/ext directory:


C:/java/jre1.6.0/lib/ext/mysql-connector.jar

Cch np Database Driver?


DriverManager np registered database driver:
1. T ng i vi type 4 & 5.
2. Load the driver class trong chng trnh:
Class.forName("com.mysql.jdbc.Driver");
3. Thm thuc tnh jdbc.drivers

System.setProperty("jdbc.drivers",
"com.mysql.jdbc.Driver");
1. Xc nh thuc tnh jdbc.drivers trong command line:
java -Djdbc.drivers="com.mysql.jdbc.Driver" ...

JDBC API

Cc bc lm vic vi CSDL
Bc 1: np JDBC driver
Bc 2: to kt ni vi CSDL dng driver np bc

1
Bc 3: thao tc vi CSDL

Cc bc lm vic vi
CSDL

Cc bc lm vic vi CSDL
selects a specific Connection type
and instantiates it

creates Statements
for database actions

Mt s lp v phng thc c bn

DriverManager - Np cc JDBC driver vo trong b nh.


C th s dng n m cc kt ni ti mt ngun d liu.

Connection - Biu th mt kt ni n mt ngun d liu.

c dng to ra cc i tng Statement,


PreparedStatement v CallableStatement.
Statement - Biu din mt lnh SQL tnh. C th s dng

n thu v i tng ResultSet.


PreparedStatement - Mt gii php thay th hot ng

tt hn i tng Statement, thc thi mt cu lnh SQL


c bin dch trc.

JDBC Code

static final String URL = "jdbc:mysql://dbserver/world";


static final String USER = "student";
static final String PASSWORD = "secret";

//Load driver
Class.forName(JDBC-DriverName);
// 1. Get a Connection to the database.
Connection connection =
DriverManager.getConnection( URL, USER, PASSWORD );

// 2. Create a Statement
Statement statement = connection.createStatement();

// 3. Execute the Statement with SQL command.


ResultSet rs = statement.executeQuery("SELECT * FROM ...");

// 4. Use the Result.


while ( rs.next( )

String name = rs.getString("name");

Kt ni CSDL vi JDBC
java.sql.Connection l giao din chun

kt ni n cc h QTCSDL.

Mi h QTCSDL s phi ci t interface ny.

MySQL driver
mysql-connector-java-5.1.7-bin.jar
Derby driver
DB2 driver

DriverManager dng chn driver v

thit lp kt ni.

JDBC URL
Ch nh ngun d liu s kt ni

jdbc:<subprotocol>:<dsn>:<others>
Trong :
<subprotocol>: c dng xc nh trnh iu khin
kt ni vi CSDL.
<dsn>: a ch CSDL. C php ca <dsn> ph thuc vo
tng trnh iu khin c th.
<other>: cc tham s khc
V d:
jdbc:odbc:dbname l URL kt ni vi CSDL tn dbname
s dng cu ni ODBC.
jdbc:microsoft:sqlserver://hostname:1433 l URL kt ni
vi CSDL Microsoft SQL Server. Trong hostname l tn
my ci SQL Server.

23

Fig. 25.24 | Popular JDBC database URL formats.

Database URL
nnh dng chung ca database URL:
String DB_URL = "jdbc:mysql://dbserver:3306/world";
Protocol Sub-protocol Hostname Port DatabaseName
Port

l TCP port m h QTCSDL s dng lng nghe yu cu.

3306 is the default port for MySQL


dng "localhost" nu CSDL nm cng 1 my.

Database URL
hostname v port l ty chn.
i vi MySQL driver: defaults l localhost v port 3306
V d:
"jdbc:mysql://localhost:3306/world"
"jdbc:mysql://localhost/world"
"jdbc:mysql:///world"
"jdbc:mysql:/world"

Kt ni CSDL vi JDBC
url = "jdbc:mysql://hostname/database"
<<interface>>

DriverManager
getConnection( url, user,
passwd) : Connection

HSQLConnection

creates

Connection
createStatement(): Statement
close( )
isClosed( ): boolean
getCatalog( ): String

MySqlConnection

Thi hnh SQL Commands


thi hnh SQL command s dng pt

createStatement ca i tng Connection.


Statement interface nh ngha cc phng thc
thi hnh cu lnh SQL.
Statement statement = connection.createStatement( );
// execute an UPDATE command
int count = statement.executeUpdate( "UPDATE City
SET population=30000 WHERE name='Bangsaen'" );
System.out.println("Modified " + count + " records");

Th hnh cu lnh SQL


Cu lnh statement.executeQuery( ) tr v 1

ResultSet.
ResultSet l bng cha kt qu tr v ca SQL.
Statement statement = connection.createStatement();
// execute a SELECT command
ResultSet rs = statement.executeQuery(
"SELECT * FROM city WHERE id = "+id );
rs.first(); // scroll to first result
do {
String name = rs.getString(1);
// get by position
int population = rs.getInt("population"); // by name
...
} while( rs.next() );

V d:
Scanner console = new Scanner(System.in);
System.out.print("Name of city to find? ");
String name = console.nextLine().trim();
String query =
"SELECT * FROM city WHERE Name='"
+name+ "'";
ResultSet rs = statement.executeQuery( query
);

ResultSet Methods
ResultSet cha cc "row" tr v t cu query.
ResultSet h tr cc phng thc ly d liu t

ct:

"get" by column number -- starts at 1 (not 0)!

"get" by column name -- field names in table/query.

String query = "SELECT * FROM Country WHERE ...";


ResultSet rs = statement.executeQuery( query );
// go to first row of results
get by column number
rs.first( );
// display the values
get by name
System.out.println( rs.getString( 1 ) );
System.out.println( rs.getInt( "population" ) );

ResultSet Methods
ResultSet h tr cc phng thc ly

tng dng v ct trong kt qu tr v


ResultSet
next() : boolean
previous() : boolean
first() : boolean
last() : boolean
absolute( k )
getInt( name: String )
getInt( index: int )
...

go to next row of results. "false" if no more.


go to previous row. "false" if 1st result.
go to first row of results.
go to last row of results.
go to k-th row of results.
get int value of field "name"
get int value of k-th column in a record

ResultSet Methods for Getting


Data
ResultSet "get" methods return column data:
getLong( 3 ) : get by column index (most efficient)
getLong( "population" ) : get by field name (safest)
getInt( ), getLong( )
- get Integer field value
getFloat( ), getDouble() - get floating pt. value
getString( ) - get Char or Varchar field value
getDate( )
- get Date or Timestamp field value
getBoolean( ) - get a Bit field value
getBytes( )
- get Binary data
getBigDecimal( ) - get Decimal field as BigDecimal
getBlob( )
- get Binary Large Object
getObject( ) - get any field value

Thi hnh cu lnh SQL Commands


Statement interface nh ngha nhiu phng thc
Resultset rs =
statement.executeQuery("SELECT ...");

use for statements that return data values (SELECT)

int count =
statement.executeUpdate("UPDATE ...");

use for INSERT, UPDATE, and DELETE

boolean b =
statement.execute("DROP TABLE test");

use to execute any SQL statement(s)

Cc bc lm vic vi CSDL
Thao tc vi CSDL:

V d minh ha JDBC ODBC

Connection

myCon;

Statement

myStatement;

ResultSet

myResultSet;

String

sUsername, sPassword;

try {
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
myCon = DriverManager.getConnection("jdbc:odbc:ThuchanhJ2EE", "", "");
myStatement = myCon.createStatement();
myResultSet = myStatement.executeQuery("Select * from Account");

V d minh ha - JDBC ODBC


while (myResultSet.next())

sUsername = myResultSet.getString(1);
sPassword = myResultSet.getString(2);
if (sUsername.equals("admin") && sPassword.equals("admin"))
return true;
}
myResultSet.close(); myStatement.close();
}
catch(Exception e) {
System.out.println(e.toString());
}

myCon.close();

JDBC Driver SQL Server 2000

Connection

myCon;

Try {
// JDBC Driver for SQL Server 2000
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
myCon = DriverManager.getConnection("jdbc:microsoft:sqlserver://hntin:1433;
DatabaseName=ThuchanhJ2EE; User=sa; Password=sa");

}
catch (Exception e) {

JDBC Driver SQL Server 2000


Lu :

Cn ci t SQL Server Service Pack 4 trc khi dng


JDBC Driver kt ni trc tip n SQL Server

Kim tra xem cng 1433 ca SQL Server m cha


bng cch vo ca s dng lnh g telnet
<hostname> 1433

PreparedStatement
i tng PreparedStatement cha 1 cu

lnh SQL c bin dch trc.

Khi thc thi DBMS khng cn phi bin dch cu


lnh SQL.

Thng c dng vi cc cu lnh SQL c

tham s.

39

PreparedStatements
c to ra t i tng Connection.
V d i tng PreparedStatement c cha 2 tham

s:
SELECT lastName, firstName, title +
FROM authors, titles, authorISBN +
WHERE authors.authorID = authorISBN.authorID +
AND titles.ISBN = authorISBN.isbn AND +
lastName = ? AND firstName = ? );

Cung cp gi tr cho tham s ca


PreparedStatement
Trc khi thi hnh, chng ta cn cung cp

gi tr cho tham s trong i tng


PreparedStatement.
Thc hin thng qua cc phng thc
setXXX.
authorBooks.setString( 1, Deitel );
authorBooks.setString( 2, Paul );

41

V d

42

Lp Qun L DB Connection
To lp ConnectionManager with a static factory method
ConnectionManager
- connection : Connection
+getConnection( ) : Connection
+close( ) : void

// example how to use


Statement statement =
ConnectionManager.getConnection().createStatement( );

Simple version of manager (1)


public class ConnectionManager {
// literal constants in Java code is baaaad code.
// we will change to a configuration file later.
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://hostname/world";
private static String user = "student";
private static String password = "student";
/* a single shared database connection */
private static Connection connection = null;
private ConnectionManager() { /* no object creation */ }

Simple version of
ConnectionManager (2)
/* the public accessor uses lazy instantiation */
public static Connection getConnection( ) throws ... {
if ( connection == null ) connection = makeConnection();
return connection;
}

Simple version of
ConnectionManager
(2)
private static Connection makeConnection( )
throws SQLException {
try {
Class.forName( driver );
// load the database driver class
connection = DriverManager.getConnection(
url, user, password );
} catch ( FileNotFoundException ex ) {
logger.error("connection error", ex ); // Logging
throw new SQLException( ex );
}
}
/* the public accessor uses lazy instantiation */
public static Connection getConnection( ) throws ... {
if ( connection == null ) connection = makeConnection();
return connection;
}

ResultSet
ResultSet gn kt vi 1 statement v 1 connection.

Nu statement or connection b ng, kt qu s


mt

Nu thi hnh cu query khc, kt qu mt

ResultSet thay i sau khi thi hnh cu query


ResultSet c th cp nht database

Statement stmt = connection.createStatement(


ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE );
ResultSet rs = statement.executeQuery( query );

ResultSet cp nht database


Xc nh thuc tnh

ResultSet.CONCUR_UPDATABLE khi to Statement.


i hi s h tr ca database driver
// rs is scrollable, will not show changes made
// by others, and will be updatable
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE );
ResultSet rs = statement.executeQuery( query );
rs.next();
int population = rs.getInt("population");
// add 10,000 to the population
rs.updateInt( "population", population+10000 );
rs.updateRow( );

JTable
Swing object hin th d liu di dng bng.

A JTable

JTable Class Diagram


JTable hin th kt qu tr v bi TableModel.
AbstractTableModel
getColumnCount( ) : int
getColumnName( index ) : String
getColumnClass( index ) : Class
getRowCount( ) : int
getValueAt( row, col ) : Object

JTable

TableModel
describes data in the
table

Design a TableModel for Queries


Design a TableModel to manage a ResultSet
AbstractTableModel
getColumnCount( ) : int
getColumnName( index ) : String
getColumnClass( index ) : Class
getRowCount( ) : int
getValueAt( row, col ) : Object

JTable

ResultSetTableModel
ResultSetTableModel(statement)
runQuery( query : String )

Ci t TableModel
ResultSet cha d liu cn hin th.
class ResultSetTableModel extends AbstractTableModel {
private Statement statement;
private ResultSet rs;
public Object getValueAt(int row, int col) {
if ( rs == null ) return null;
rs.absolute( row + 1 );
rs.getObject( col );
}
public int getRowCount() {
if ( rs == null ) return 0;
rs.last();
rowCount = rs.getRow();
return rowCount;
}

// move to last row

Implementing TableModel (2)


ResultSet is missing some information.
public int getColumnCount( ) {
}
public String getColumnName( int col ) {

ResultSet Meta-data
ResultSet c getMetaData( )tr v cc thng tin.
ResultSetMetaData cha thng tin miu t.

try {
ResultSet resultSet =
statement.executeQuery( query );
ResultSetMetaData metadata = resultSet.getMetaData();
int numberOfColumns = metadata.getColumnCount();
for(int col=1; col<=numberOfColumns; col++) {
// get name and SQL datatype for each column
String name = metadata.getColumnName( col );
int type = metadata.getColumnType( col );
int typeName = metadata.getColumnTypeName( col );
} catch( SQLException sqle ) { ... }

Closing the Connection


Khuyn co nn ng connection sau khi hon

tt
Connection connection = DriverManager.getConnection(...);
/* use the database */
...
/* done using database */
public void close( ) {
if ( connection == null ) return;
try {
connection.close();
}
catch ( SQLException sqle ) { /* ignore it */ }
finally { connection = null; }
}

You might also like