Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 95

Database Connectivitive

JDBC
Chapter’s Objectives
1. Introduction
2. The Design of JDBC
3. The Structured Query Language
4. Installing JDBC
5. Basic JDBC Programming Concepts
6. Executing Queries
7. Scrollable and Updatable Result Sets
8. Metadata
9. Row Sets
10. Transactions
11. Advanced Connection Management

© 2006 by Ton Phuoc


Part 1: Introduction

© 2006 by Ton Phuoc


Introduction (1)

 Database
 Collection of data
 DBMS
 Database management system
 Stores and organizes data
 SQL
 Relational database
 Structured Query Language

© 2006 by Ton Phuoc


Introduction (2)

 RDBMS
 Relational database management system
 Relational database
 Table
 Rows, columns
 Primary key
 Unique data

© 2006 by Ton Phuoc


Introduction (3)

 Example: Employee table

Number Name Department Salary Location

23603 Jones 413 1100 New Jersey

24568 Kerwin 413 2000 New Jersey


Row 34589 Larson 642 1800 Los Angeles
35761 Myers 611 1400 Orlando

47132 Neumann 413 9000 New Jersey


78321 Stephens 611 8500 Orlando

Primary key Column

© 2006 by Ton Phuoc


ODBC overview (1)

 ODBC is an API introduced by Microsoft that allows


applications to access databases by using SQL.
 By using ODBC, a single application can access remote
databases under different DBMSs (i.e. Informix, Oracle,
Sybase)
 ODBC relies on data drivers to convert the ODBC calls to
different database formats.

© 2006 by Ton Phuoc


ODBC overview (2)

 At development time, the application developer only needs to know the


ODBC calls to connect to a database, execute SQL statements, and
retrieve results.
 Main Components of ODBC:
 Application
 Driver manager
 Driver
 Target-database middleware

© 2006 by Ton Phuoc


ODBC overview (3)

 Application :
 Requests a connection with a target database
 Passes one or more SQL statements
 Processes the produced results or error conditions
 Ends each transaction with a commit or rollback
 Terminates the connection.

© 2006 by Ton Phuoc


ODBC overview (4)

 Driver Manager:
 Loads drivers on an as-needed basis for applications
 Maps a target database name to a specific driver
 Processes several ODBC initialization calls
 Validates the parameters and sequences of ODBC calls

© 2006 by Ton Phuoc


ODBC overview (5)

 Driver :
 Processes the ODBC function calls
 Modifies them to the target database format
 Submits the SQL statements to the target database, receives the
results, and presents the results to the application.

© 2006 by Ton Phuoc


ODBC overview (6)

 Target-Database Middleware :
 Includes the database needed by the applications and the
associated middleware
 Database may be located on the same machine or remote machine.

© 2006 by Ton Phuoc


The Design of JDBC (1)

 JDBC is a Java-based counterpart to ODBC


 JDBC provides a standard API for tool/database developers
and makes it possible to write database applications using a
pure Java API.
 Database developers will supply JDBC drivers for their
databases so that Java programs may access them
transparently.

© 2006 by Ton Phuoc


JDBC (2)

 ODBC is not appropriate for direct use from Java because it uses a C
interface. (security, implementation, robustness, portability)
 A literal translation of the ODBC C API into a Java API would not be
desirable. (void pointers)
 JDBC is easier to learn.
 A Java API like JDBC is needed in order to enable a “pure java”
solution.

© 2006 by Ton Phuoc


JDBC Objects
and interfaces Java to C

DB
JDBC-
Java JDBC specifics
ODBC
Appl. Runtime
Driver
ODBC
RDBMS
Driver
Initialization,
ODBC APIs Driver bindings

Windows
ODBC ODBC
3G/4G
Interface Runtime
Appl.

© 2006 by Ton Phuoc


JDBC (3)

© 2006 by Ton Phuoc


JDBC (4)

 JDBC drivers are classified into the following types:


 type 1 driver translates JDBC to ODBC and relies on an ODBC driver to communicate with
the database.
 type 2 driver is a driver, written partly in the Java programming language and partly in
native code, that communicates with the client API of a database. When you use such a
driver, you must install some platform-specific code in addition to a Java library.
 type 3 driver is a pure Java client library that uses a database-independent protocol to
communicate database requests to a server component, which then translates the
requests into a database-specific protocol. The client library is independent of the actual
database, thus simplifying deployment.
 type 4 driver is a pure Java library that translates JDBC requests directly to a database-
specific protocol.

© 2006 by Ton Phuoc


Typical Uses of JDBC (1)

© 2006 by Ton Phuoc


Typical Uses of JDBC (2)

© 2006 by Ton Phuoc


STRUCTURED QUERY LANGUAGE(1)

 JDBC is an interface to SQL, which is the interface to


essentially all modern relational databases.
 You can think of a database as a bunch of named tables with
rows and columns. Each column has a column name. The
rows contain the actual data. These are sometimes called
records.

© 2006 by Ton Phuoc


STRUCTURED QUERY LANGUAGE(2)

 There are 3 types of SQL language :


 DDL : data definition language.
 DML : data manipulation language.
 DCL(Transact-SQL): data control language.

© 2006 by Ton Phuoc


Installing JDBC (1)

 On Windows, it already include the JDBC/ODBC bridge


driver.
 We can use driver for Ms Access without installing any thing.
 With MS SQL Server 2000, we must install the driver to use
for accessing data.

© 2006 by Ton Phuoc


Installing JDBC (2)

 To configure ODBC data source, follow these steps:


 Open windows Administrative tools
 Open “Data Sources (ODBC)”.
 Add new Data source.
 Select Driver : Microsoft Access Driver(*.mdb).
 Enter data source name.
 Select your database from specifie folder.
 Press OK to finish.

© 2006 by Ton Phuoc


Basic JDBC Programming Concepts (1)

 Database URLs:
 When connecting to a database, you must specify the data source and you may
need to specify additional parameters.
 Syntax:
 Jdbc:subprotocol name:other_stuff
subprotocol is used to select the specific driver for connecting to the database.
The format for the other stuff parameter depends on the subprotocol used. You need
to look up your vendor's documentation for the specific format.
 Example : jdbc:odbc:your_Datasource

© 2006 by Ton Phuoc


Basic JDBC Programming Concepts (2)

 Making the Connection:


1. Using url to specify the Driver manager:
 Ex: String url=
“sun.jdbc.odbc.JdbcOdbcDriver”;
Class.forName(url);
2. Putting database URL:
 Ex: String dbURL=
"jdbc:odbc:yourDataSource";
3. Create Connection object:
 Ex: Connection conn = DriverManager.getConnection(dbURL);

© 2006 by Ton Phuoc


Basic JDBC Programming Concepts (3)

 Connect to Microsoft Access


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver=
{Microsoft Access Driver (*.mdb)};DBQ=yourDB.mdb";
Connection conn =
DriverManager.getConnection( database,"Admin","");
//do something after connect…

© 2006 by Ton Phuoc


Connect to Microsoft SQLServer 2000

© 2006 by Ton Phuoc


 Examples:
o myJDBC_Connect.class
o access.java
o testConnect_01.java

© 2006 by Ton Phuoc


Basic JDBC Programming Concepts (4)

 Executing SQL Commands :


1. To execute a SQL command, you first create a Statement object.
Statement statement = conn.createStatement();
2. Next, place the statement that you want to execute into a string :
String sqlCMD=“…”;
3. Then you call the executeXXX method.
statement.execcuteXXX(sqlCMD);

© 2006 by Ton Phuoc


Basic JDBC Programming Concepts (5)

 Execute methods of Statement object:


1. ExecuteUpdate(…) : exec a non return value query
(delete,insert,update…queries).
2. executeQuery(…) : Execute and return a set of records.
3. executeBatch() : execute a batch of commands.
4. Execute(…) : multipurpose command to execute any types of
SQL command.

© 2006 by Ton Phuoc


Basic JDBC Programming Concepts (6)

 ResultSet object :
 Get a set of records after execute a sql command.
ResultSet rs = statement.executeQuery(sql);
 Using getXXX() methods to get specify values from ResultSet
Ex : String id=rs. getString(“StudentID”);
 Parameters in getXXX() methods can be a database field name or the index
of DB field. Database column numbers start at 1.

© 2006 by Ton Phuoc


Basic JDBC Programming Concepts (7)

 ResultSet object :
 Traverse through ResulSet :
while(rs.next()){
process(rs.getXX(“fieldName”));
}
 Each getXXX() method will make reasonable type conversions
when the type of the method doesn't match the type of the column.
 SQL data types and Java data types are not exactly the same. See
below:

© 2006 by Ton Phuoc


Basic JDBC Programming Concepts (8)

© 2006 by Ton Phuoc


Advanced SQL Types (JDBC 2)

 In addition to numbers, strings, and dates, many databases can store


large objects such as images or other data. In SQL, binary large objects
are called BLOBs, and character large objects are called CLOBs.
 The getBlob and getClob methods return objects of type BLOB and
CLOB. These classes have methods to fetch the bytes or characters in
the large objects.

© 2006 by Ton Phuoc


Advanced SQL Types (JDBC 2)

 When you get a BLOB or an array from a database, the actual contents
are only fetched from the database when you request individual values.
This is a useful performance enhancement, since the data can be quite
voluminous.
 Some databases are able to store user-defined structured types. JDBC
2 supports a mechanism for automatically mapping structured SQL
types to Java objects.

© 2006 by Ton Phuoc


Part 2:
Working with JDBC

© 2006 by Ton Phuoc


Executing Queries (1)

Execute select sql statement :


ResultSet rs=statement.executeQuery(sql);
Ex:
String sql=“select * from tblStudent”;
ResultSet rs=statement.executeQuery(sql);
Or:
String sql=
“select * from tblStudent where studentID like ‘sv%’”;
ResultSet rs=statement.executeQuery(sql);

© 2006 by Ton Phuoc


Executing Queries (2)

Execute insert,update, delete sql statement


int recNum=statement.executeUpdate(sql);
Ex:
String sql=“insert into tblClass values( ‘CDTH5A’, ’Cao dang TH 5A’,120,’Nguyễn
Văn Bình’,’cntt’)”;
int recNum=statement.executeUpdate(sql);
Or:
String sql=“delete from tblClass where classID=‘CDTH5A’”;
int recNum=statement.executeUpdate(sql);
Or:
String sql=“update tblClass set studentsNum=100 where
classID=‘CDTH5A’”;
int recNum=statement.executeUpdate(sql);

© 2006 by Ton Phuoc


Executing Queries (3)

Execute sql statement with parameters


 Using parameters in your sql statement likes sample follow :
String pSql=“select * from tblClass where classID=?”
 To passing parameter in this case, we must use PrepareStatement
objecct instead using Statement object.

© 2006 by Ton Phuoc


Executing Queries (4)
Example:
String pSql=“select * from tblClass where classID=?”
PreparedStatement QueryStat =
conn.prepareStatement(pSql);
 Before executing the prepared statement, you must bind the host
variables to actual values with a setXXX() method.
Ex: setString(1, ‘CDTH4C’);
 The position 1 denotes the first “?” and so on.

© 2006 by Ton Phuoc


Executing Queries (5)

 If you reuse a prepared query that you have already executed and
the query has more than one host variable, all host variables stay
bound as you set them unless you change them with a set
method.
 Once all variables have been bound to values, you can execute
the query
ResultSet rs = QueryStat.executeQuery();

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (1)

Scrollable Result Sets :


 To obtain scrolling result sets from your queries, you must obtain a
different Statement object with the method:
Statement stat = conn.createStatement(rs_type, concurrency);
 For a prepared statement, use the call
PreparedStatement stat = conn.prepareStatement(command, rs_type,
concurrency);

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (2)

ResultSet type values :

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (3)

ResultSet concurrency values

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (4)

 For example, if you simply want to be able to scroll through a


result set but you don't want to edit its data, you use:
Statement stat =
conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stat.executeQuery(query)

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (5)

 After create the scrollable ResultSet, we can scrolling is very


simple:
 rs.next(); //move next record.
 rs.previous(); //move previous record.
 rs.relative(n); //move the cursor over n record(s).
 rs.first(); //move to first record.
 rs.last(); //move to last record.
 rs.absolute(n); //set the cursor to a row nth.
 int n = rs.getRow();//gets the number of the current
//row. Rows are numbered starting with 1.
 rs.beforeFirst();//before the first position.
 rs.afterLast();// after the last position.

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (6)

Test whether the cursor is at one of these special positions:


 rs.isFirst();
 rs.isLast();
 rs.isBeforeFirst();
 rs.isAfterLast();

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (7)

 Updatable Result Sets :


 If you want to be able to edit result set data and have the
changes automatically reflected in the database, you need to
create an updatable result set.
 Updatable result sets don't have to be scrollable, but if you
present data to a user for editing, you usually want to allow
scrolling as well.

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (8)

 To obtain updatable result sets, you create a statement as follows.


Statement stat =
conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
 Then, the result sets returned by a call to executeQuery are
updatable. You can use updateXXX() methods of ResultSet to
update specify field.
 Ex:
rs.updateString(“className", “your enter class Name”);
rs.updateRow();

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (9)

Insert new row to ResultSet:


1. rs.moveToInsertRow(); //create new insert row
2. Call rs.updateXXX(“fieldName”,value) methods.
3. Call rs.insertRow() ;//actual insert row
4. Call rs.moveToCurrentRow();//move to previous row.

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (10)

 You can delete the row under the cursor:


rs.deleteRow();
 The deleteRow method immediately removes the row from
both the result set and the database.

© 2006 by Ton Phuoc


Scrollable and Updatable Result Sets (11)

 The updateRow, insertRow, and deleteRow methods of the ResultSet


class give you the same power as executing UPDATE, INSERT, and
DELETE SQL commands.
 If you are not careful, you can write staggeringly inefficient code with
updatable result sets. It is much more efficient to execute an UPDATE
statement than it is to make a query and iterate through the result,
changing data along the way.

© 2006 by Ton Phuoc


part 3:
Advanced JDBC programming

© 2006 by Ton Phuoc


CallableStatement (1)

 A CallableStatement object provides a way to call stored procedures in


a standard way for all RDBMSs.
 This call is written in an escape syntax that may take one of two forms:
 One form with a result parameter.
 And the other without one.
 Both forms may have a variable number of parameters used for input
(IN parameters), output (OUT parameters), or both (INOUT
parameters).

© 2006 by Ton Phuoc


CallableStatement (2)

 The syntax for invoking a stored procedure in JDBC is


shown here.
{call procedure_name[(?, ?, ...)]}
 The syntax for a procedure that returns a result
parameter is:
{? = call procedure_name[(?, ?, ...)]}
 The syntax for a stored procedure with no parameters
would look like this:
{call procedure_name}

© 2006 by Ton Phuoc


CallableStatement (3)

 Creating a CallableStatement Object :


 CallableStatement objects are created with the Connection method
prepareCall :
CallableStatement cstmt = con.prepareCall(
"{call procedureName(?, ?)}");
Note: The “?” placeholders are IN, OUT, or INOUT parameters
depends on the stored procedure procedureName.

© 2006 by Ton Phuoc


CallableStatement (4)

 IN Parameters :
 Passing in any IN parameter values to a CallableStatement
object is done using the setXXX methods inherited from
PreparedStatement. The type of the value being passed in
determines which setXXX method to use. For example:
CallableStatement cs=con.prepareCall("{call
qClass_Dept(?)}");
cs.setString(1,“cntt");
View sample : callStatement_01.java

© 2006 by Ton Phuoc


CallableStatement (5)

 OUT Parameters :
 If the stored procedure returns OUT parameters, the JDBC type of each OUT
parameter must be registered before the CallableStatement object can be
executed
 Registering the JDBC type is done with the method registerOutParameter. Then
after the statement has been executed, CallableStatement's getXXX methods
can be used to retrieve OUT parameter values.

© 2006 by Ton Phuoc


Ex:
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, 3);
View Sample : callStatement_02.java
callStatement_03.java

© 2006 by Ton Phuoc


CallableStatement (6)

 Numbering of Parameters :
 CallableStatement cstmt = con.prepareCall(
"{call getTestData(25, ?)}"); cstmt.registerOutParameter(1,
java.sql.Types.TINYINT);

© 2006 by Ton Phuoc


CallableStatement (7)

 INOUT Parameters :
 A parameter that supplies input as well as accepts output (an
INOUT parameter) requires a call to the appropriate setXXX
method (inherited from PreparedStatement) in addition to a call to
the method registerOutParameter. The setXXX method sets a
parameter's value as an input parameter, and the method
registerOutParameter registers its JDBC type as an output
parameter.

© 2006 by Ton Phuoc


CallableStatement cstmt =
con.prepareCall( "{call reviseTotal(?)}");
cstmt.setByte(1, 25);
cstmt.registerOutParameter(1,
java.sql.Types.TINYINT);
cstmt.executeUpdate();
byte x = cstmt.getByte(1);

© 2006 by Ton Phuoc


Metadata (1)

 JDBC can give you additional information about the structure


of a database and its tables. For example, you can get a list
of the tables in a particular database or the column names
and types of a table.
 Objective:
 Understand about database metadata.
 Using JDBC to get these informations

© 2006 by Ton Phuoc


Metadata (2)

 In SQL, data that describes the database or one of its parts is


called metadata (to distinguish it from the actual data that is
stored in the database). You can get two kinds of metadata:
about a database and about a result set.
 The details of its will be descript as follow.

© 2006 by Ton Phuoc


Metadata (3)

 Getting Information about a Result Set :


 When you send a SELECT statement using JDBC, you get back a
ResultSet object containing the data that satisfied your criteria. You can
get information about this ResultSet object by creating a
ResultSetMetaData object and invoking ResultSetMetaData methods on it.
Ex:
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from tblClass");
ResultSetMetaData rsmd = rs.getMetaData() ;

© 2006 by Ton Phuoc


Metadata (4)

 Gets count of columns in ResultSet:


int numCols = rsmd.getColumnCount();
 Gets list of column name:
String []colNames=new String[numCols];
for (int i = 0; i<numCols; i++){
colNames [i]=rsmd.getColumnName(i+1);
}
 View sample getColumnName.java

© 2006 by Ton Phuoc


Metadata (5)

 Get Table Name


String tableName=rsmd.getTableName(i);
 Get Column data type
int jdbcType=rsmd.getColumnType(i);
String DBMSname = rsmd.getColumnTypeName(i);
 Checking nullable
int nullable=rsmd.isNullable(i);
return value:
ParameterMetaData.parameterNoNulls, ParameterMetaData.parameterNullable, or
ParameterMetaData.parameterNullableUnknown
 View sample :getColumnType.java

© 2006 by Ton Phuoc


Metadata (6)

 Getting Information about a Database or Database System :


 Once you have an open connection with a DBMS, you can create a
DatabaseMetaData object that contains information about that
database system. Using the Connection object con, the following
line of code creates the DatabaseMetaData object dbmd:
DatabaseMetaData dbmd = con.getMetaData();

© 2006 by Ton Phuoc


Metadata (7)

Methods:
ResultSet rs=dbmd.getTables(String catalog, String
schemaPattern, String tableNamePattern, String types[]);
Gets a description of all tables in a catalog that match the
schema and table name patterns and the type criteria.
A Schema describes a groups of related table and access
permissions. A Catalog describes a related groups of
schemas.

© 2006 by Ton Phuoc


Metadata (8)

 Ex: page 241.


 String[]tblType={“TABLE”};
 ResultSet rs=dbmd.getTables(null,null,null,tblType);
 The types array contains the names of the table types to include.
Typical types are TABLE, VIEW, SYSTEM TABLE, GLOBAL
TEMPORARY, LOCAL TEMPORARY, ALIAS, and SYNONYM. If types
is null, then tables of all types are returned.
 View sample : getAllDBTable.java

© 2006 by Ton Phuoc


Metadata (9)

Methods:
getColumns(String catalog, String schemaPattern, String
tableNamePattern, String columnNamePattern);
Retrieves a description of table columns available in the specified catalog.
 Ex:
ResultSet columnName=metadata.getColumns
(null,null,tableName,null);
 View sample: getTableInfos.java

© 2006 by Ton Phuoc


Metadata (11)

 Design sample application:


1. Retrieve all table in database.
2. For each table in database, gets all informations.
3. Display result using GUI.
View sample :metaDataDEMO.jar

© 2006 by Ton Phuoc


Metadata (11)

 Another way to retrieve metadata


o We can use sql command to retrieve infos from metadata.
o Example, in SQL Server, we can use system table
(sysObjects, sysTables, sysColumns,…) and support
procedures (sp_help, sp_table,…) to get all infos about
catalog, schema, database, table and so on).
o View sample : getMetaData.java

© 2006 by Ton Phuoc


© 2006 by Ton Phuoc
Row Sets

 The RowSet interface extends the ResultSet interface, but


row sets don't have to be tied to a database connection.
 The javax.sql.rowset package provides the following
interfaces that extend the RowSet interface:
o CachedRowSet
o WebRowSet
o FilteredRowSet and JoinRowSet
o JdbcRowSet

© 2006 by Ton Phuoc


CachedRowSet (1)

 A CachedRowSet allows disconnected operation.


 A cached row set contains all data from a result set.
 You can close the connection and still use the row set.
 Each user command simply opens the database connection,
issues a query, puts the result in a row set, and then closes
the database connection.

© 2006 by Ton Phuoc


CachedRowSet (2)

 You can modify the data in a cached row set.


 The modifications are not immediately reflected in the
database.
 You need to make an explicit request to accept the
accumulated changes.
 The CachedRowSet reconnects to the database and issues
SQL commands to write the accumulated changes.

© 2006 by Ton Phuoc


CachedRowSet (3)

 Cached row sets are not appropriate for large query results.
 You can populate a CachedRowSet from a result set:

© 2006 by Ton Phuoc


CachedRowSet (4)

 You can let the CachedRowSet object establish a connection


automatically. Set up the database parameters:
rowset.setURL(myURL); rowset.setUsername("username");
rowset.setPassword(“myPSW");

© 2006 by Ton Phuoc


CachedRowSet (5)

 If you modified the row set contents, you must write it back to
the database by calling
rowset.acceptChanges(conn);
or
rowset.acceptChanges();

© 2006 by Ton Phuoc


CachedRowSet (6)

 A row set that contains the result of a complex query will not
be able to write back changes to the database.
 You should be safe if your row set contains data from a single
table.

© 2006 by Ton Phuoc


CachedRowSet (7)

 Using a cached row set, the program logic is now greatly


simplified.
o We simply open and close the connection in every action listener.
o We no longer need to trap the "window closing" event to close the
connection.
o We no longer worry whether the result set is scrollable. Row sets
are always scrollable.

© 2006 by Ton Phuoc


Other rowsets
 A WebRowSet is a cached row set that can be saved to an XML file.
The XML file can be moved to another tier of a web application, where it
is opened by another WebRowSet object.
 The FilteredRowSet and JoinRowSet interfaces support lightweight
operations on row sets that are equivalent to SQL SELECT and JOIN
operations. These operations are carried out on the data stored in row
sets, without having to make a database connection.
 A JdbcRowSet is a thin wrapper around a ResultSet. It adds useful
getters and setters from the RowSet interface, turning a result set into a
"bean."

© 2006 by Ton Phuoc


© 2006 by Ton Phuoc
Transaction (1)

 The major reason for grouping commands into transactions is database


integrity.
 If you group updates to a transaction, then the transaction either
succeeds in its entirety and it can be committed, or it fails somewhere in
the middle. In that case, you can carry out a rollback and the database
automatically undoes the effect of all updates that occurred since the
last committed transaction.

© 2006 by Ton Phuoc


Transaction (2)

 By default, a database connection is in autocommit mode,


and each SQL command is committed to the database as
soon as it is executed. Once a command is committed, you
cannot roll it back.
 To check the current autocommit mode setting, call the
getAutoCommit() method of the Connection class.

© 2006 by Ton Phuoc


Transaction (3)

 Implementing transaction:
1. You turn off autocommit mode with the command:
conn.setAutoCommit(false);
2. Now you create a statement object in the normal way: Statement
stat =
conn.createStatement();
3. Call executeUpdate any number of times.
4. When all commands have been executed, call the commit method:
conn.commit();
5. However, if an error occurred, call
conn.rollback();

© 2006 by Ton Phuoc


Transaction (4)

 Batch Updates :
 Use the supportsBatchUpdates method of the
DatabaseMetaData class to find out if your database supports
this feature.
 The commands in a batch can be actions such as INSERT,
UPDATE, and DELETE as well as data definition commands
such as CREATE TABLE and DROP TABLE.
 However, you cannot add SELECT commands to a batch
since executing a SELECT statement returns a result set.

© 2006 by Ton Phuoc


Transaction (5)

1. To execute a batch, you first create a Statement object in the


usual way:
Statement statment = conn.createStatement();
2. Now, instead of calling executeUpdate, you call the addBatch
method:
String sqlCommand = ". . ."
statement.addBatch(sqlCommand);
3. Finally, you submit the entire batch:
int[] counts = stat.executeBatch();

© 2006 by Ton Phuoc


Transaction (6)

 For proper error handling in batch mode, you want to treat the batch
execution as a single transaction. If a batch fails in the middle, you want
to roll back to the state before the beginning of the batch.
 First, turn autocommit mode off, then collect the batch, execute it,
commit it, and finally restore the original autocommit mode.
 See example as follow:

© 2006 by Ton Phuoc


Transaction (7)

try{
boolean autoCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
Statement stat = conn.getStatement();
...
// keep calling stat.addBatch(. . .);
...
stat.executeBatch();
conn.commit();
conn.setAutoCommit(autoCommit);
}catch(SQLException sqlEx){
conn.rollback();
}

© 2006 by Ton Phuoc


Advanced Swing components(1)

 JTable:
 DefaultTableModel:
 DefaultTableModel dtm=new DefaultTableModel(title,numRows);
 String[]Title={“”,””,…};
 JTable tbl=new JTable(dtm);
 Set table header
 tbl.getTableHeader().setXXX(…);

© 2006 by Ton Phuoc


Advanced Swing components(2)

 JTable: (cont.)
 Add row :
 Object obj[]=new Object[i];
 dtm.addRow(obj);
 Remove row:
 dtm. removeRow(i);
 Clear table:
 dtm.setRowCount(0);

© 2006 by Ton Phuoc


Advanced Swing components(1)

 JSplitPane
 JSplitPane(int Direction,Componet first, Component seconds);
 Direction :HORIZONTAL_SPLIT or VERTICAL_SPLIT

© 2006 by Ton Phuoc


THE END.

© 2006 by Ton Phuoc

You might also like