// The driver has to be in the classpath.. Class.forName"org.apache.derby.jdbc.ClientDriver"; }catch ClassNotFoundException cnfe{ System.out.println"" + cnfe; } 10 B2... // PreparedState
Trang 1Chuyên đ 2
L p trình JSP, Servlet
Bài 02: C b n v JDBC
Gi ng viên: ThS Tr nh Tu n t
B môn CNPM Email: trinhtuandat.bk@gmail.com/dattt@soict.hut.edu.vn
B môn Công ngh Ph n m m
Vi n CNTT & TT
Tr ng i h c Bách Khoa Hà N i
N i dung
1 JDBC là gì?
2 Cức b c s d ng API c a JDBC
3 DataSource & k thu t Connection Pooling
4 Transaction
5 Prepared & Callable Statements
2
1 JDBC là gì?
3
JDBC là gì?
Là cức API Java chu n t c đ truy c p CSDL quan h
ng d ng không c n quan tâm t i chi ti t c th
c a CSDL
N m trong Java SE (J2SE)
Java SE 6 có phiên b n JDBC 4
4
JDBC API
nh ngh a m t t p cức Java Interfaces, đ c cài
đ t b i cức vendor khức nhau, thành cức JDBC
Drivers
Cức ng d ng s d ng t p cức giao di n này đ th c
hi n cức thao tức v i CSDL Tính portability
Ph n l n API c a JDBC n m trong gói java.sql
DriverManager, Connection, ResultSet,
DatabaseMetaData, ResultSetMetaData,
PreparedStatement, CallableStatement và Types
M t s ch c n ng nâng cao khức n m trong gói
javax.sql package
DataSource
JDBC Driver
Là cài đ t c th c a cức JDBC interfaces
T t c cức database server đ u có JDBC driver(s)
t ng ng
Có th xem danh sứch cức drivers đã có trên
http://industry.java.sun.com/products/jdbc/drivers
Trang 2Database URL
c s d ng đ t o m t k t n i t i database
Có th ch a server, port, protocol, etc.
Cú pháp:
jdbc: subprotocol_name :driver_dependant_databasename
Ví d :
Oracle thin driver
jdbc: oracle:thin : @machinename:1521:dbname
Derby
jdbc: derby ://localhost:1527/sample
Pointbase
jdbc: pointbase : server://localhost/sample
7
2 Cức b c s d ng JDBC API
8
Cức b c s d ng JDBC
B1 Load JDBC driver cho t ng lo i CSDL
B2 L y đ i t ng Connection
B3 L y đ i t ng Statement
B4 Th c hi n câu truy v n, câu l nh update
B5 c k t qu tr v
B6 c cức Meta-data (tùy ch n)
B7 óng đ i t ng Statement và đ i t ng
Connection
9
B1 Load JDBC driver cho t ng lo i CSDL
load v driver cho CSDL và đ ng ký nó
v i DriverManager, c n load class t ng ng
Class.forName(<database-driver>)
try { // This loads an instance of the Pointbase DB Driver.
// The driver has to be in the classpath.
Class.forName("org.apache.derby.jdbc.ClientDriver");
}catch (ClassNotFoundException cnfe){
System.out.println("" + cnfe);
}
10
B2 L y ra đ i t ng Connection
L p DriverManager ch u trứch nhi m t o k t n i t i
CSDL
S d ng DataSource là cứch hay dùng h n khi mu n l y
ra m t đ i t ng connection (trình bày ph n sau)
Ví d t o k t n i t i CSDL nh sau:
try {
Connection connection = DriverManager
getConnection("jdbc:derby://localhost:1527/sample",
“app"," app ");
} catch(SQLException sqle) {
System.out.println("" + sqle);
}
11
DriverManager & Connection
java.sql.DriverManager
getConnection(String url, String user, String password) throws SQLException
java.sql.Connection
Statement createStatement() throws SQLException
void close() throws SQLException
void setAutoCommit(boolean b) throws SQLException
void commit() throws SQLException
void rollback() throws SQLException
12
Trang 3B3 L y ra đ i t ng Statement
T o m t đ i t ng Statementt đ i t ng
Connection
java.sql.Statement
ResultSet executeQuery(string sql)
int executeUpdate(String sql)
Ví d :
Statement statement = connection.createStatement();
Cùng đ i t ng Statementcó th đ c dùng
cho nhi u queries không liên quan t i nhau
13
B4 Th c thi cức câu truy v n/cức l nh
T đ i t ng Statement, 2 l nh đ c s
d ng nhi u nh t là
(a) QUERY (SELECT)
ResultSet rs = statement.executeQuery("select * from customer_tbl");
int iReturnValue = statement.executeUpdate("update manufacture_tbl set name = ‘IBM' where mfr_num = 19985678");
14
B5 X lý k t qu nh n v
Duy t trên ResultSetđ x lý thông tin
java.sql.ResultSet
boolean next()
xxx getXxx(int columnNumber)
xxx getXxx(String columnName)
void close()
u tiên, con tr l p n m tr c hàng đ u
tiên
LTV c n g i ph ng th c next() đ chuy n con
tr đ n hàng đ u tiên
15
B5 X lý k t qu nh n v (2)
Khi đã có ResultSet, LTV d dàng x lý d
li u
L u ý: Ch s c a ResultSet b t đ u t 1
while (rs.next()){
// Wrong this will generate an error String value0 = rs.getString(0);
// Correct!
String value1 = rs.getString(1);
int value2 = rs.getInt(2);
int value3 = rs.getInt(“ADDR_LN1");
}
16
B5 X lý k t qu nh n v (3)
Mu n l y d li u t ResultSet, s d ng
ph ng th c getXXX() cho phù h p
getString()
getInt()
getDouble()
getObject()
M i ki u d li u trong java.sql.Types, đ u có
ph ng th c getXXX t ng ng
B6 c metadata c a ResultSet và metadata c a CSDL (tùy ch n)
Khi đã có đ i t ng ResultSet ho c Connection, LTV có th l y v metadata c a CSDL ho c c a câu truy v n
em l i thông tin h u ích v d li u l y
v , ho c v CSDL đang s d ng
ResultSetMetaData rsMeta = rs.getMetaData();
DatabaseMetaData dbmetadata = connection.getMetaData();
Có kho ng 150 ph ng th c trong l p DatabaseMetaData
Trang 4Ví d v ResultSetMetaData
ResultSetMetaData meta = rs.getMetaData();
//Return the column count
int iColumnCount = meta.getColumnCount();
for (int i =1 ; i <= iColumnCount ; i++){
System.out.println(“Column Name: " + meta.getColumnName(i) );
System.out.println(“Column Type" + meta.getColumnType(i) );
System.out.println("Display Size: " + meta.getColumnDisplaySize(i) );
System.out.println("Precision: " + meta.getPrecision(i) );
System.out.println(“Scale: " + meta.getScale(i) );
}
19
3 DataSource & k thu t Connection Pooling
20
3 DataSource & k thu t Connection Pooling
3.1 Giao di n DataSource và đ i t ng DataSource
3.2 Cức thu c tính c a đ i t ng DataSource
3.3 ng ký JNDI c a đ i t ng DataSource
3.4 Connection Pooling
3.5 L y v đ i t ng DataSource
21
3.1 Giao di n javax.sql.DataSource và đ i
t ng DataSource
T ng nhà cung c p Driver s th c thi cài đ t interface
i t ng DataSource dùng đ t o cức k t
n i CSDL (database connections)
22
Giao di n javax.sql.DataSource và đ i
t ng DataSource
Có 3 ki u cài đ t interface
Basic implementation : cung c p đ i t ng
Connection chu n t c
Connection pooling implementation : cung c p đ i
t ng Connection t đ ng n m trong connection
pooling
Distributed transaction implementation : cung c p
đ i t ng Connection có th dùng đ c cho cức
giao d ch (transactions) phân tứn, h u h t n m
trong connection pooling
23
3.2 Cức thu c tính c a đ i t ng DataSource
M t đ i t ng DataSource có cức thu c tính có th s a
đ i khi c n thi t-đ c đ nh ngh a trong file c u hình
c a container
a ch c a database server
Tên c a database
Network protocol đ c s d ng đ giao ti p v i server
L i ích: vì thay đ i đ c thu c tính c a DataSource, cức
đo n code truy c p t i DataSource đó không c n thay
đ i
Trong Sun Java System Application Server (và GlassFish V2), m t data source đ c g i là m t JDBC resource
24
Trang 5Cức thu c tính c a m t DataSource đ c
đ nh ngh a đâu?
Trong file c u hình c a container
Trong Sun Java System App Server:
<J2EE_HOME>/domains/domain1/config/domain
.xml
Trong Tomcat:
<TOMCAT_HOME>/conf/server.xml
25
DataSource (JDBC Resource) trong file domain.xml c a Sun Java System App Server
<resources>
<jdbc-resource enabled="true" jndi-name="jdbc/BookDB"
object-type="user" pool-name="PointBasePool"/>
<jdbc-connection-pool connection-validation-method="auto-commit" datasource-classname="com.pointbase.xa.xaDataSource"
fail-all-connections="false" idle-timeout-in-seconds="300"
is-connection-validation-required="false" is-isolation-level-guaranteed="true" max-pool-size="32" max-wait-time-in-millis="60000" name="PointBasePool" pool-resize-quantity="2"
res-type="javax.sql.XADataSource" steady-pool-size="8">
<property name="DatabaseName"
value="jdbc:pointbase:server://localhost:9092/sun-appserv-samples"/>
<property name="Password" value="pbPublic"/>
<property name="User" value="pbPublic"/>
</jdbc-connection-pool>
</resources>
26
nh ngh a DataSource trong Sun Java
System App Server
27
nh ngh a DataSource trong Sun Java System App Server (2)
28
3.3 ng ký JNDI c a đ i t ng
DataSource
M t driver đ c truy c p t m t đ i t ng
DataSource s không đ ng ký nó v i
DriverManager
Th c t , m t đ i t ng DataSource đ c
đ ng ký v i JNDI naming service nh
container và tr v cho client qua thao tức
tra c u (lookup operation)
V i ki u basic implementation, k t n i l y
đ c t đ i t ng DataSource là gi ng v i
k t n i l y đ c t DriverManager
3.3 ng ký JNDI c a đ i t ng DataSource (JDBC Resource)
nh danh JNDI c a m t JDBC resource có d ng
java:comp/env/jdbc
Ví d : JNDI name cho BookDB database
java:comp/env/jdbc/BookDB
Vì t t c cức đ nh danh JNDI c a cức resource đ u
có d ng java:comp/env, nên khi c n ch ra đ nh danh JNDI c a m t JDBC resource, ch c n nh p vào jdbc/name
Ví d : jdbc/BookDB
Trang 63.4 T i sao c n Connection Pooling?
K t n i CSDL là tài nguyên có chi phí cao, và
b h n ch
S d ng connection pooling, ch c n 1 s nh cức
connections có th đ c dùng chung cho 1 s
l n clients
T o và h y cức k t n i CSDL là thao tức có
chi phí cao
S d ng connection pooling, có s n m t t p cức
k t n i s n dùng, h n ch t o m i/h y cức
connection
31
3.5 L y và s d ng đ i t ng DataSource
ng d ng th c hi n thao tức tra c u JNDI ( JNDI lookup ) đ l y v đ i t ng DataSource
i t ng DataSource sau đó dùng đ l y ra đ i
t ng Connection
Trong file web.xml c a ng d ng, c n ch ra thông tin v external resource , & v đ i t ng DataSource
Trong Sun Java System App server , c n ứnh x
gi a external resource v i JNDI name
T ng tính flexibility
32
Ví d : L y đ i t ng DataSource qua
JNDI
BookDBAO.java trong ng d ng bookstore1
( http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets3.html )
public class BookDBAO {
private ArrayList books;
Connection con;
private boolean conFree = true;
public BookDBAO() throws Exception {
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/BookDB");
con = ds.getConnection();
} catch (Exception ex) {
throw new Exception("Couldn't open connection to database: " +
ex.getMessage());
}
}
33
Thông tin v JNDI Resource trong file web.xml
c a ng d ng bookstore1
<resource-ref>
<res-ref-name>jdbc/BookDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
34
Mapping gi a JNDI và Resource trong file
sun-web.xml
<sun-web-app>
<context-root>/bookstore1</context-root>
<resource-ref>
<res-ref-name>jdbc/BookDB</res-ref-name>
<jndi-name>jdbc/BookDB</jndi-name>
</resource-ref>
</sun-web-app>
35
4 Transaction
36
Trang 7 Vi c commit t ng câu l nh m t ngay khi
đ c yêu c u tiêu t n nhi u th i gian
Khi thi t l p AutoCommit là false, LTV có th
c p nh t CSDL nhi u l n, sau đó commit
toàn b trong m t transaction
Ngoài ra, n u cức l nh ph thu c l n nhau,
toàn b transaction có th đ c rolled back
37
Cức ph ng th c trong JDBC Transaction
setAutoCommit()
N u thi t l p là true, t t c cức l nh th c thi (executed statement) s đ c commit ngay l p t c
commit()
Ch h p l khi đã thi t l p setAutoCommit(false)
Commit t t c cức thao tức đ c th c hi n, t lúc m
m t Connection ho c t l i g i commit() ho c rollback()
g n nh t
rollback()
Ch h p l khi đã thi t l p setAutoCommit(false)
H y t t c cức thao tức v a th c hi n
38
Ví d v Transactions
Connection connection = null;
try {
connection =
DriverManager.getConnection("jdbc:oracle:thin:@machinenam e:1521:db
name","username","password");
connection.setAutoCommit(false);
PreparedStatement updateQty =
connection.prepareStatement("UPDATE STORE_SALES SET QTY = ?
WHERE ITEM_CODE = ? ");
39
Ví d v Transactions (2)
int [][] arrValueToUpdate = { {123, 500} ,
{124, 250}, {125, 10}, {126, 350} };
int iRecordsUpdate = 0;
for ( int items=0 ; items < arrValueToUpdate.length ; items++) { int itemCode = arrValueToUpdate[items][0];
int qty = arrValueToUpdate[items][1];
40
Ví d v Transactions (3)
updateQty.setInt(1,qty);
updateQty.setInt(2,itemCode);
iRecordsUpdate += updateQty.executeUpdate();
}
connection.commit();
System.out.println(iRecordsUpdate +
" record(s) have been updated");
} catch(SQLException sqle) {
System.out.println("" + sqle);
Ví d v Transactions (4)
try {
connection.rollback();
} catch(SQLException sqleRollback) { System.out.println("" + sqleRollback);
} } finally { try { connection.close();
} catch(SQLException sqleClose) { System.out.println("" + sqleClose);
} }
Trang 85 Prepared &
Callable Statements
43
nh ngh a?
PreparedStatement
Câu l nh SQL đ c g i đ n CSDL, đ c biên d ch
ho c đ c chu n b tr c
CallableStatement
Th c thi cức SQL Stored Procedures
44
PreparedStatement
ôi khi, nhi u câu l nh có c u trúc t ng t
nhau, ch có giứ tr là thay đ i
PreparedStatement có th đ c s d ng đ
so n tr c câu l nh có c u trúc c n thi t
PreparedStatement có th nh n cức tham s
VÀO, ho t đ ng t ng t cức đ i s cho m t
ph ng th c
45
Cức b c làm vi c v i PreparedStatement
B1: T o DB connection nh bình th ng
B2: T o đ i t ng prepared statement t connection
PreparedStatement updateSales = con.prepareStatement(“UPDATE OFFER_TBL SET QUANTITY = ? WHERE ORDER_NUM = ? ");
// “?” are referred to as Parameter Markers // Parameter Markers are referred to by number, // starting from 1, in left to right order
// PreparedStatement's setXXX() methods are used to set // the IN parameters, which remain set until changed
46
Cức b c làm vi c v i PreparedStatement (2)
B3 Truy n vào cức đ i s theo đúng v trí
updateSales.setInt(1, 75);
updateSales.setInt(2, 10398001);
B4 Th c thi prepared statement
int iUpdatedRecords =
updateSales.executeUpdate();
47
Cức b c làm vi c v i PreparedStatement (3)
N u thu c tính AutoCommit là true, khi th c thi câu l nh, thay đ i s đ c commit T đó
v sau, có th s d ng l i đ i t ng Prepared Statement này
updateSales.setInt(1, 150);
48
Trang 9 N u đ i t ng prepared statement có ki u là câu
l nh select, sau khi th c thi và l y v k t qu , ti n
hành duy t trên ResultSet nh ph n tr c
PreparedStatement itemsSold =
con.prepareStatement("select o.order_num,
o.customer_num, c.name, o.quantity from order_tbl
o, customer_tbl c where o.customer_num =
c.customer_num and o.customer_num = ?;");
itemsSold.setInt(1,10398001);
ResultSet rsItemsSold = itemsSold.executeQuery();
while (rsItemsSold.next()){
System.out.println( rsItemsSold.getString(“NAME")
+ " sold "+ rsItemsSold.getString(“QUANTITY") + "
unit(s)");
CallableStatement
Là giao di n đ c s d ng đ th c thi cức
SQL stored procedures
M t stored procedure là m t nhóm cức câu
l nh SQL th c hi n m t công vi c nào đó
m t t p cức thao tức ho c truy v n trên m t database server
50
CallableStatement (2)
M t đ i t ng CallableStatement ch a l i g i
đ n m t stored procedure; nó không ch a
chính stored procedure này
Ví d : g i đ n stored procedure
SHOW_SUPPLIERS s d ng connection con
và tr v ResultSet
CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
51
Ví d CallableStatement
Ví d s d ng cức tham s IN, OUT và INOUT
// set int IN parameter
cstmt.setInt( 1, 333 );
// register int OUT parameter
cstmt.registerOutParameter( 2, Types.INTEGER );
// set int INOUT parameter
cstmt.setInt( 3, 666 );
// register int INOUT parameter
cstmt.registerOutParameter( 3, Types.INTEGER );
//You then execute the statement with no return value
cstmt.execute(); // could use executeUpdate()
// get int OUT and INOUT
int iOUT = cstmt.getInt( 2 );
Ví d Stored Procedure
FUNCTION event_list (appl_id_in VARCHAR2,
dow_in VARCHAR2,
event_type_in VARCHAR2 OUT,
status_in VARCHAR2 INOUT)
RETURN ref_cur;
Ví d v i Oracle DB
try { Connection connection = DriverManager.getConnection("");
CallableStatement queryreport = connection.prepareCall("{
? = call SRO21208_PKG.QUEUE_REPORT ( ? , ? , ? , ? , ? , ? ) }");
queryreport.registerOutParameter(1,OracleTypes.CURSOR); queryreport.setInt(2,10);
queryreport.setString(3, "000004357");
queryreport.setString(4, "01/07/2003");
queryreport.setString(5, "N");
queryreport.setString(6, "N");
queryreport.setInt(8, 2);
Trang 10Ví d v i Oracle DB
queryreport.execute();
ResultSet resultset = (ResultSet)queryreport.getObject(1);
while (resultset.next())
{
System.out.println("" + resultset.getString(1) + " "
+ resultset.getString(2));
}
}
catch( SQLException sqle){
System.out.println("" + sqle);
}
55