You are on page 1of 39

Java DataBase Connectivity_ JDBC

Tài liệu tham khảo:


http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html
http://java.sun.com/docs/books/tutorial/jdbc/jdbc2dot0/index.html

1
Nội dung bài học
† Tìm hiểu JDBC API và các JDBC Drivers
† Mô hình 2-tier và 3-tier
† Các bước truy xuất CSDL dùng JDBC
† Các ví dụ minh hoạ
† Transactions

Sau bài học này, sinh viên có thể viết được các chương
trình truy xuất CSDL bằng ngôn ngữ Java

2
JDBC API
† JDBC API viết tắt của
Java Database
Connectivity Application
Programming Interface
† Cung cấp các lớp và các
interface để hổ trợ Java
program có thể truy
xuất database

3
JDBC Drivers
† Giúp cho các ứng dụng truy
xuất CSDL theo một chuẩn
chung không phục thuộc vào
DBMS
† JDBC Driver nhận các requests
từ client, converts sang dạng
mà Database có thể hiểu
được. Ngược lại, JDBC Driver
sẽ nhận các response, dịch
sang Java data format, để
client application có thể hiểu
được -> Java-to-SQL
translator

4
java.sql package
† Chứa các interfaces và classes được định
nghĩa trong JDBC API để access database
† Các Interfaces của java.sql package:
„ CallableStatement „ PreparedStatement
„ Connection „ ResultSet
„ DatabaseMetaData „ ResultSetMetaData
„ Driver „ Statement

Các exception :
DataTruncation, SQLException và SQLWarning

5
JDBC Drivers
† JDBC driver thích hợp với mô hình client/server
† Có 4 loại JDBC drivers:
„ JDBC-ODBC Bridge
„ Native API Java
„ JDBC Network
„ Native Protocol

6
JDBC-ODBC Bridge

† Được hổ trợ
bởi JavaSoft.
† Dùng được cho
nhiều
databases.
† Sử dụng dịch
vụ DataSource
ODBC
7
Native-API-Partly-Java Driver
† Sử dụng local native
libraries để trao đổi với
database bằng cách
dùng CLI (Call Level
Interface)
† Khi client gởi request,
driver sẽ dịch JDBC
request sang native
method call và chuyển
request cho native CLI

8
JDBC-Net-All-Java Driver
† Khác với 2 drivers trước là vị trí của native
database access libraries
† Native CLI libraries được đặt trên remote
server và driver dùng network protocol
cho việc trao đổi giữa application và driver
† Driver được chia thành 2 phần: một phần
chứa tất cả các phần Java mà có thể
download về cho client và phần server
chứa cả hai Java và native methods

9
Native-Protocol-All-Java Driver

† 100% Java và không dùng CLI libraries

† Có khả năng trao đổi với database một


cách trực tiếp mà không cần translation

10
Two-Tier Client Server Model
† Một kiến trúc cho môi
trường client-server là
two-tier system (client là
tầng thứ nhất, server là
tầng thứ hai)
† Trong môi trường two-
tier JDBC, database
application là client và
DBMS là server
† Client trao đổi trực tiếp
với server

11
Two-Tier Client Server Model [Contd...)
† Ưu điểm:
„ Không phức tạp.
„ Duy trì một kết nối cố định giữa client và
database.
„ Thời gian để thực hiện một ứng dụng bằng mô
hình two-tier nhanh hơn three-tier
† Khuyết điểm:
„ Hầu hết các driver (native libraries) cần dùng
phải load về cho client -> client bị nặng
„ Khó nâng cấp

12
Three-Tier Client Server Model
[Contd...)
† Three-tier client-server environment

13
Three-Tier Client Server Model
† Lớp thứ ba đóng vai trò điều khiển các
requests từ client và chuyển chúng cho
database server -> proxy
† Ưu:
„ Tách database server ra khỏi server
application
„ Dễ nâng cấp

14
CÁC BƯỚC TRUY XUẤT
CSDL
1. Import java.sql package
2. Load và đăng ký driver
3. Thiết lập connection đến
database server
4. Tạo đối tượng
statement:
Statement/PreparedStat
ement/CallableStatemen
t
5. Thực hiện lệnh SQL
6. Nhận kết quả trả về và
xử lý
7. Đóng statement và
connection

15
Thiết lập connection đến
database

† Lớp java.sql.DriverManager cung cấp


các phương thức để load drivers:

static Connection getConnection(String url)


Attempts to establish a connection to the given database URL.
static Connection getConnection(String url, Properties info)
Attempts to establish a connection to the given database URL.
static Connection getConnection(String url, String user, String pass)
Attempts to establish a connection to the given database URL.
static Driver getDriver(String url)
Attempts to locate a driver that understands the given URL.

16
Interface Connection (1)
† Mô tả một kết nối với một CSDL cụ thể
† Đối tượng Connection có thể cung cấp các thông tin
mô tả về các tables, các SQL grammar được hổ trợ,
các stored procedures, … bằng phương thức
getMetaData để trả về đối tượng DatabaseMetaData.
void close(): close the connection.
void commit() : commit database
Statement createStatement(): Creates a Statement object for sending
SQL statements to the database.
Statement createStatement(int resultSetType, int resultSetConcurrency)
Creates a Statement object that will generate ResultSet objects with the
given type and concurrency.

17
Interface Connection (2)
CallableStatement prepareCall(String sql)
Creates a CallableStatement object for calling database stored
procedures.
CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency)
Creates a CallableStatement object that will generate ResultSet objects
with the given type and concurrency.
PreparedStatement prepareStatement(String sql)
Creates a PreparedStatement object for sending parameterized SQL
statements to the database.
PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency)
Creates a PreparedStatement object that will generate ResultSet
objects with the given type and concurrency.
18
Interface Connection (3)
void rollback()
Undoes all changes made in the current transaction and releases any
database locks currently held by this Connection object.
void rollback(Savepoint savepoint)
Undoes all changes made after the given Savepoint object was set.
void setAutoCommit(boolean autoCommit)
Sets this connection's auto-commit mode to the given state.

19
Interface Statement (1)
† Được dùng để thực hiện một lệnh SQL tỉnh. Nếu câu
lệnh SQL là lệnh truy vấn (select.. ) thì kết quả trả về
là một đối tượng Resultset
† Default, một đối tượng ResultSet chỉ tương ứng với
một đối tượng Statement đang mở tại một thời điểm.

void close() : close đối tượng statement


ResultSet executeQuery(String sql)
Executes the given SQL statement, which is select statement
int executeUpdate(String sql)
Executes the given SQL statement, which may be an INSERT,
UPDATE, or DELETE statement or an SQL statement that returns nothing,
such as an SQL DDL statement.

20
Ví dụ chương trình để tạo table Departments gồm 2
field: DepID và DepName trong file
HRManagement.mdb dùng JDBC-ODBC driver

1. Taïo file HRManagement.mdb


• 2. Thieát laäp Data source ODBC vôùi data source name
(DSN) laø DATA (khoâng baét buoäc phaûi truøng teân file
mdb)
•3. Vieát chöông trình Java ñeå thöïc hieän truy xuaát CSDL

21
Chương trình mã nguồn Java

Import java.sql.*;
public class TaoTable1 {
public static void main(String[] args) {
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //load driver
Connection cn = DriverManager.getConnection(“jdbc:odbc:data”);
Statement st = cn.createStatement(); // taïo statement
String sql = “create tabel Departments (depID text(10) primary key,
depName text(50) not null) “;
st.executeUpdate(sql); // thöïc hieän lệnh SQL
st.close(); cn.close(); // ñoùng keát noái
}catch(Exception e){} } // main} //class

22
Lưu ý
† Neáu câu leänh sql laø leänh select thì phaûi duøng phöông thöùc
executeQuery() cuûa ñoái töôïng statement vaø keát quaû traû veà seõ
laø moät ñoái töôïng ResultSet.
† Neáu leänh sql khoâng laø leänh select thì phaûi duøng phöông thöùc
executeUpdate() cuûa ñoái töôïng statement vaø keát quaû traû veà seõ
moät soá nguyeân.
† Xem theâm caùc interface vaø caùc lôùp Connection, Statement,
PreparedStatement, CallableStatement, ResultSet

23
Vieát chöông trình ñeå insert moät record cho table
departments

try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url =“jdbc:odbc:data” ;
Connection cn = DriverManager.getConnection(url);
Statement st = cn.createStatement();
String sql = “insert into departments (depID, depName) values (‘ns’,
‘phoøng nhaân söï ‘)“;
st.executeUpdate(sql);
st.close(); cn.close();
}catch(Exception e){}
} // main } //class

24
Interface ResultSet
† Được tạo ra từ phương thức executeQuery() của các
đối tượng Statement, PreparedStatement,
CallableStatement..
† Chứa các dữ liệu được trả về từ lệnh select query
† chứa một cursor chỉ đến record hiện hành. Khi
resultset vừa được tạo ra, cursor sẽ chỉ đến before the
first record
† Dùng phương thức next() để di chuyển cursor đến
record kế tiếp, nếu đến after the last record thì trả về
giá trị false
† Default, ResultSet là readOnly và forward only

25
Các phương thức thường dùng
(1)
boolean first()
Moves the cursor to the first row in this ResultSet object.
boolean getBoolean(int columnIndex)
Retrieves the value of the designated column in the current row of
this ResultSet object as a boolean in the Java programming language.
boolean getBoolean(String columnName)
Retrieves the value of the designated column in the current row of
this ResultSet object as a boolean in the Java programming language.
byte getByte(int columnIndex)
Retrieves the value of the designated column in the current row of
this ResultSet object as a byte in the Java programming language.
byte getByte(String columnName)
Retrieves the value of the designated column in the current row of
this ResultSet object as a byte in the Java programming language.
26
Các phương thức thường dùng
(2)
Date getDate(int columnIndex)
Retrieves the value of the designated column in the current row of
this ResultSet object as a java.sql.Date object in the Java programming
language.
Date getDate(String columnName)
Retrieves the value of the designated column in the current row of
this ResultSet object as a java.sql.Date object in the Java programming
language.
double getDouble(int columnIndex)
Retrieves the value of the designated column in the current row of
this ResultSet object as a double in the Java programming language.
double ge tDouble(String columnName)
Retrieves the value of the designated column in the current row of
this ResultSet object as a double in the Java programming language.

27
Các phương thức thường dùng
(3)
float getFloat(int columnIndex): Retrieves the value of the designated column in
the current row of this ResultSet object as a float in the Java programming
language.
float getFloat(String columnName): Retrieves the value of the designated column
in the current row of this ResultSet object as a float in the Java programming
language.
int getInt(int columnIndex): Retrieves the value of the designated column in the
current row of this ResultSet object as an int in the Java programming language.
int getInt(String columnName): Retrieves the value of the designated column in
the current row of this ResultSet object as an int in the Java programming
language.
long getLong(int columnIndex): Retrieves the value of the designated column in
the current row of this ResultSet object as a long in the Java programming
language.
long getLong(String columnName):Retrieves the value of the designated column
in the current row of this ResultSet object as a long in the Java programming
28
Các phương thức thường dùng
(4)
ResultSetMetaData getMetaData(): Retrieves the number, types and
properties of this ResultSet object's columns.
String getString(int columnIndex): Retrieves the value of the
designated column in the current row of this ResultSet object as a String
in the Java programming language.
String getString(String columnName): Retrieves the value of the
designated column in the current row of this ResultSet object as a String
in the Java programming language.
boolean last(): Moves the cursor to the last row in this ResultSet object.
boolean next():Moves the cursor down one row from its current position.
boolean previous():Moves the cursor to the previous row in this
ResultSet object.

29
Vieát chöông trình lieät keâ caùc record trong table
departments

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url =“jdbc:odbc:data” ;
Connection cn = DriverManager.getConnection(url);
Statement st = cn.createStatement();
String sql = “select * from departments “;
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
System.out.println(“ DepID : “ + rs.getString(“depid”));
System.out.println(“DepName : “ +
rs.getString(“depName”)); }
st.close(); cn.close();

30
Interface ResultSetMetaData

† Cung cấp các hằng và các methods được dùng để


lấy các thông tin về đối tượng ResultSet.
int getColumnCount():Returns the number of columns in this ResultSet
String getColumnLabel(int column) : Gets the designated column's
suggested title for use in printouts and displays.
String getColumnName(int column): Get the designated column's name.
int getColumnType(int column): Retrieves the designated column's SQL
type.
String getColumnTypeName(int column) : Retrieves the designated
column's database-specific type name.
String getTableName(int column): Gets the designated column's table
name.

31
Ví dụ dùng
ResultSetMetadata
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn = DriverManager.getConnection("jdbc:odbc:data");
Statement st = cn.createStatement();
String sqlstr= "select * from departments";
ResultSet rs =st.executeQuery(sqlstr);
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
for (int i=1;i<=rsmd.getColumnCount();i++)
{
System.out.println(rsmd.getColumnLabel(i) +
": " + rs.getString(i));
}
}

32
Interface
PreparedStatement
† Là interface con của Statement.
† Câu lệnh SQL được precompiled và stored trong
PreparedStatement object và có thể được thực hiện nhiều
lần.
† Câu lệnh SQL có thể có nhiều tham số, và có nhiều lệnh
setXXX(index, value) để đặt giá trị cho tham số.
Ví dụ:
PreparedStatement pstmt = con.prepareStatement("UPDATE
EMPLOYEES SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00) ;
pstmt.setInt(2, 110592) ;
(Xem thêm interface PreparedStatement)

33
Interface
CallableStatement (1)
† Dùng để thực hiện một stored procedure
† Là interface con của Statement và
preparedStatement
† Có thể truyền tham số cho stored
procedure, tham số thứ nhất có index là 1
† Cú pháp để thực hiện một a stored
procedure
CallableStatement cs
= con.prepareCall("{call
<Proc_name>}");

34
Interface
CallableStatement (2)
† Cú pháp gọi procedure có tham số
truyền vào:
{call procedure_name[(?, ?, ...)]}
† Cú pháp gọi procedure có tham số trả
giá trị về:
{? = call procedure_name[(?, ?, ...)]}

35
Ví dụ gọi thực hiện một stored
procedure có tham số truyền vào
CallableStatement cstmt =
con.prepareCall( "{call updatePrices(?, ?)}");
cstmt.setString(1, "Colombian");
cstmt.setFloat(2, 8.49f);
cstmt.executeUpdate();
cstmt.setString(1, "Colombian_Decaf");
cstmt.setFloat(2, 9.49f);
cstmt.executeUpdate();

36
Ví dụ thực hiện một stored
procedure có tham số trả giá
trị về
CallableStatement cstmt = con.prepareCall( "{call getTestData(?, ?)}");
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.registerOutParameter(2, java.sql.Types.DECIMAL, 3);
ResultSet rs = cstmt.executeQuery();
// . . . retrieve result set values with rs.getXXX methods
byte x = cstmt.getByte(1);
java.math.BigDecimal n = cstmt.getBigDecimal(2);

37
Transaction
† Khi chúng ta muốn thực hiện một dãy các lệnh cập
nhật CSDL và muốn rằng lệnh trước hoàn thành chỉ
khi lệnh các lệnh sau đó cũng phải hoàn thành ->
dùng transaction
† Khi một connection sau khi được tạo thì chế độ Auto
commit được bật lên.
† Muốn tạo ra một transaction, ta phải tắt chế độ này:
con.setAutoCommit(false);
† Nếu các lệnh trong transaction đều thực hiện thành
công thì gọi phương thức commit của connection
† Nếu có một lệnh trong transaction không thực hiện
được, dùng phương thức rollback để rollback
transaction

38
ví dụ về transaction
try{ con.setAutoCommit(false); // bắt đầu transaction
PreparedStatement updateSales = con.prepareStatement( "UPDATE
COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal = con.prepareStatement( "UPDATE
COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit(); // kết thúc transaction thành công
con.setAutoCommit(true);
}catch( Exception e){ con.rollback(); }

39

You might also like