Professional Documents
Culture Documents
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
JDBC
JDBC
JDBC
3
CSDL
Ti sao cn JDBC?
JDBC gip cc Java Developers to nn cc ng dng
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
JDBC-ODBC
nhim
JDBC-ODBC Library
JDBC-ODBC Library
ODBC
ODBC
Driver
Driver
Database
Database
Database
Database
tip
vi
JDBC
middleware
trn
server.
JDBC Driver Type 3
JDBC Driver Type 3
Network protocol
JDBC Middleware
JDBC Middleware
(java)
(java)
Database
Database
hin
thc/dng
database
nht.
Chuyn li gi JDBC thnh cc
li gi giao thc DBMS c th.
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
JDBC Code
//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();
Kt ni CSDL vi JDBC
java.sql.Connection l giao din chun
kt ni n cc h QTCSDL.
MySQL driver
mysql-connector-java-5.1.7-bin.jar
Derby driver
DB2 driver
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
Database URL
nnh dng chung ca database URL:
String DB_URL = "jdbc:mysql://dbserver:3306/world";
Protocol Sub-protocol Hostname Port DatabaseName
Port
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
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:
ResultSet Methods
ResultSet h tr cc phng thc ly
int count =
statement.executeUpdate("UPDATE ...");
boolean b =
statement.execute("DROP TABLE test");
Cc bc lm vic vi CSDL
Thao tc vi CSDL:
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");
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();
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) {
PreparedStatement
i tng PreparedStatement cha 1 cu
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 = ? );
41
V d
42
Lp Qun L DB Connection
To lp ConnectionManager with a static factory method
ConnectionManager
- connection : Connection
+getConnection( ) : Connection
+close( ) : void
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.
JTable
Swing object hin th d liu di dng bng.
A JTable
JTable
TableModel
describes data in the
table
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;
}
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 ) { ... }
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; }
}