Professional Documents
Culture Documents
Database Connectivitive JDBC
Database Connectivitive JDBC
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
Database
Collection of data
DBMS
Database management system
Stores and organizes data
SQL
Relational database
Structured Query Language
RDBMS
Relational database management system
Relational database
Table
Rows, columns
Primary key
Unique data
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.
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
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.
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.
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.
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.
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
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.
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:
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.
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();
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
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.
Numbering of Parameters :
CallableStatement cstmt = con.prepareCall(
"{call getTestData(25, ?)}"); cstmt.registerOutParameter(1,
java.sql.Types.TINYINT);
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.
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.
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
Cached row sets are not appropriate for large query results.
You can populate a CachedRowSet from a result set:
If you modified the row set contents, you must write it back to
the database by calling
rowset.acceptChanges(conn);
or
rowset.acceptChanges();
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.
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();
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.
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:
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();
}
JTable:
DefaultTableModel:
DefaultTableModel dtm=new DefaultTableModel(title,numRows);
String[]Title={“”,””,…};
JTable tbl=new JTable(dtm);
Set table header
tbl.getTableHeader().setXXX(…);
JTable: (cont.)
Add row :
Object obj[]=new Object[i];
dtm.addRow(obj);
Remove row:
dtm. removeRow(i);
Clear table:
dtm.setRowCount(0);
JSplitPane
JSplitPane(int Direction,Componet first, Component seconds);
Direction :HORIZONTAL_SPLIT or VERTICAL_SPLIT