You are on page 1of 39

Java DataBase Connectivity_ JDBC

Ti liu tham kho: http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html http://java.sun.com/docs/books/tutorial/jdbc/jdbc2dot0/index.html

Ni dung bi hc
Tm hiu JDBC API v cc JDBC Drivers M hnh 2-tier v 3-tier Cc bc truy xut CSDL dng JDBC Cc v d minh ho Transactions Sau bi hc ny, sinh vin c th vit c cc chng trnh truy xut CSDL bng ngn ng Java

JDBC API
JDBC API vit tt ca Java Database Connectivity Application Programming Interface Cung cp cc lp v cc interface h tr Java program c th truy xut database

JDBC Drivers
Gip cho cc ng dng truy xut CSDL theo mt chun chung khng phc thuc vo DBMS JDBC Driver nhn cc requests t client, converts sang dng m Database c th hiu c. Ngc li, JDBC Driver s nhn cc response, dch sang Java data format, client application c th hiu c -> Java-to-SQL translator

java.sql package
Cha cc interfaces v classes c nh ngha trong JDBC API access database Cc Interfaces ca java.sql package:
CallableStatement Connection DatabaseMetaData Driver PreparedStatement ResultSet ResultSetMetaData Statement

Cc exception : DataTruncation, SQLException v

SQLWarning
5

JDBC Drivers
JDBC driver thch hp vi m hnh client/server C 4 loi JDBC drivers: JDBC-ODBC Bridge

Native API Java JDBC Network Native Protocol

JDBC-ODBC Bridge
c h tr bi JavaSoft. Dng c cho nhiu databases. S dng dch v DataSource ODBC
7

Native-API-Partly-Java Driver
S dng local native libraries trao i vi database bng cch dng CLI (Call Level Interface) Khi client gi request, driver s dch JDBC request sang native method call v chuyn request cho native CLI

JDBC-Net-All-Java Driver
Khc vi 2 drivers trc l v tr ca native database access libraries Native CLI libraries c t trn remote server v driver dng network protocol cho vic trao i gia application v driver Driver c chia thnh 2 phn: mt phn cha tt c cc phn Java m c th download v cho client v phn server cha c hai Java v native methods

Native-Protocol-All-Java Driver
100% Java v khng dng CLI libraries C kh nng trao i vi database mt cch trc tip m khng cn translation

10

Two-Tier Client Server Model


Mt kin trc cho mi trng client-server l two-tier system (client l tng th nht, server l tng th hai) Trong mi trng twotier JDBC, database application l client v DBMS l server Client trao i trc tip vi server
11

Two-Tier Client Server Model [Contd...)


u im: Khng phc tp. Duy tr mt kt ni c nh gia client v database. Thi gian thc hin mt ng dng bng m hnh two-tier nhanh hn three-tier Khuyt im: Hu ht cc driver (native libraries) cn dng phi load v cho client -> client b nng Kh nng cp

12

Three-Tier Client Server Model [Contd...)


Three-tier client-server environment

13

Three-Tier Client Server Model


Lp th ba ng vai tr iu khin cc requests t client v chuyn chng cho database server -> proxy u: Tch database server ra khi server application D nng cp

14

CC BC CSDL
1. 2. 3. 4. Import java.sql package Load v ng k driver Thit lp connection n database server To i tng statement: Statement/PreparedStat ement/CallableStatemen t Thc hin lnh SQL Nhn kt qu tr v v x l ng statement v connection

TRUY

XUT

5. 6. 7.

15

Thit lp connection n database


Lp java.sql.DriverManager cung cp cc phng thc 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 mt kt ni vi mt CSDL c th i tng Connection c th cung cp cc thng tin m t v cc tables, cc SQL grammar c h tr, cc stored procedures, bng phng thc getMetaData tr v i tng 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 dng thc hin mt lnh SQL tnh. Nu cu lnh SQL l lnh truy vn (select.. ) th kt qu tr v l mt i tng Resultset Default, mt i tng ResultSet ch tng ng vi mt i tng Statement ang m ti mt thi im.
void close() : close i tng 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 chng trnh to table Departments gm 2 field: DepID v DepName trong file HRManagement.mdb dng JDBC-ODBC driver 1. Tao file HRManagement.mdb 2. Thiet lap Data source ODBC vi data source name (DSN) la DATA (khong bat buoc phai trung ten file mdb) 3. Viet chng trnh Java e thc hien truy xuat CSDL

21

Chng trnh m ngun 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(); // tao statement String sql = create tabel Departments (depID text(10) primary key, depName text(50) not null) ; st.executeUpdate(sql); // thc hien lnh SQL st.close(); cn.close(); // ong ket noi }catch(Exception e){} } // main} //class
22

Lu
Neu cu lenh sql la lenh select th phai dung phng thc executeQuery() cua oi tng statement va ket qua tra ve se la mot oi tng ResultSet. Neu lenh sql khong la lenh select th phai dung phng thc executeUpdate() cua oi tng statement va ket qua tra ve se mot so nguyen. Xem them cac interface va cac lp Connection, Statement, PreparedStatement, CallableStatement, ResultSet

23

Viet chng trnh e insert mot 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, phong nhan s ); st.executeUpdate(sql); st.close(); cn.close(); }catch(Exception e){} } // main } //class
24

Interface ResultSet
c to ra t phng thc executeQuery() ca cc i tng Statement, PreparedStatement, CallableStatement.. Cha cc d liu c tr v t lnh select query cha mt cursor ch n record hin hnh. Khi resultset va c to ra, cursor s ch n before the first record Dng phng thc next() di chuyn cursor n record k tip, nu n after the last record th tr v gi tr false Default, ResultSet l readOnly v forward only

25

Cc phng thc thng dng (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

Cc phng thc thng dng (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

Cc phng thc thng dng (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

Cc phng thc thng dng (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

Viet chng trnh liet ke cac 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 cp cc hng v cc methods c dng ly cc thng tin v i tng 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 dng 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 ca Statement. Cu lnh SQL c precompiled v stored trong PreparedStatement object v c th c thc hin nhiu ln. Cu lnh SQL c th c nhiu tham s, v c nhiu lnh 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 thm interface PreparedStatement)

33

Interface CallableStatement (1)


Dng thc hin mt stored procedure L interface con ca Statement v preparedStatement C th truyn tham s cho stored procedure, tham s th nht c index l 1 C php thc hin mt a stored procedure CallableStatement cs = con.prepareCall("{call <Proc_name>}");
34

Interface CallableStatement (2)


C php gi procedure c tham s truyn vo:
{call procedure_name[(?, ?, ...)]}

C php gi procedure c tham s tr gi tr v:


{? = call procedure_name[(?, ?, ...)]}

35

V d gi thc hin mt stored procedure c tham s truyn vo


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 thc hin mt 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 chng ta mun thc hin mt dy cc lnh cp nht CSDL v mun rng lnh trc hon thnh ch khi lnh cc lnh sau cng phi hon thnh -> dng transaction Khi mt connection sau khi c to th ch Auto commit c bt ln. Mun to ra mt transaction, ta phi tt ch ny: con.setAutoCommit(false); Nu cc lnh trong transaction u thc hin thnh cng th gi phng thc commit ca connection Nu c mt lnh trong transaction khng thc hin c, dng phng thc rollback rollback transaction
38

v d v transaction
try{ con.setAutoCommit(false); // bt 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(); // kt thc transaction thnh cng con.setAutoCommit(true); }catch( Exception e){ con.rollback(); }

39

You might also like