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 procedure
Trang 1Java 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
Trang 2Nộ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
Trang 4JDBC 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
sang Java data format, để
client application có thể hiểu
được -> Java-to-SQL
translator
Trang 5java.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:
Trang 8request sang native
method call và chuyển
request cho native CLI
Trang 9JDBC-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
Trang 10Native-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
Trang 11Two-Tier Client Server Model
Một kiến trúc cho môi
Trang 12Two-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
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
Trang 13Three-Tier Client Server Model [Contd )
Three-tier client-server environment
Trang 14Three-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
Tách database server ra khỏi server
application
Dễ nâng cấp
Trang 15CÁC BƯỚC TRUY XUẤT CSDL
1 Import java.sql package
2 Load và đăng ký driver
Trang 16Thiế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)
Trang 17Interface 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
Trang 18Interface Connection (2)
CallableStatement prepareCall(String sql)
Creates a CallableStatement object for calling database stored
PreparedStatement prepareStatement(String sql)
Creates a PreparedStatement object for sending parameterized SQL statements to the database
PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency)
Trang 19Interface 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
Trang 20Interface 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,
Trang 21Ví 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 Tạo file HRManagement.mdb
• 2 Thiết lập Data source ODBC với data source name
(DSN) là DATA (không bắt buộc phải trùng tên file
mdb)
•3 Viết chương trình Java để thực hiện truy xuất CSDL
Trang 22Chươ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(); // tạo statement
String sql = “create tabel Departments (depID text(10) primary key, depName text(50) not null) “;
st.executeUpdate(sql); // thực hiện lệnh SQL
st.close(); cn.close(); // đóng kết nối
Trang 23Lưu ý
Nếu câu lệnh sql là lệnh select thì phải dùng phương thức
executeQuery() của đối tượng statement và kết quả trả về sẽ
là một đối tượng ResultSet.
Nếu lệnh sql không là lệnh select thì phải dùng phương thức
executeUpdate() của đối tượng statement và kết quả trả về sẽ một số nguyên.
Xem thêm các interface và các lớp Connection, Statement,
PreparedStatement, CallableStatement, ResultSet
Trang 24Viết chương trình để insert một record cho table
Trang 25Interface 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
Trang 26Cá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
Trang 27Cá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)
Trang 28Cá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
Trang 29Cá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
Trang 30Viết chương trình liệt kê các record trong table
Trang 31Interface 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
Trang 32Ví dụ dùng ResultSetMetadata
Trang 33Interface 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ềulầ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ố
Trang 34Interface 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
Trang 35Interface CallableStatement (2)
Cú pháp gọi procedure có tham số
Trang 36Ví dụ gọi thực hiện một stored procedure có tham số truyền vào
Trang 37Ví dụ thực hiện một stored procedure có tham số trả giá trị về
CallableStatement cstmt = con.prepareCall( "{call getTestDatẳ, ?)}");
Trang 38 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
Trang 39ví 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");