Module 5: J2EE and JDBC (Database Access) 1.java Database Connectivity (JDBC)
Module 5: J2EE and JDBC (Database Access) 1.java Database Connectivity (JDBC)
2.JDBC Drivers
To connect with individual databases, JDBC requires drivers for each database.
The various driver types are described in the following sections:
Type I: JDBC-ODBC Bridge
Type II: Native API/JAVA
Type III: Pure Java driver for database middleware(JDBC protocol)
Type Four Driver : Direct-to-database pure Java driver (JAVA protocol)
Type 1: JDBC-ODBC Bridge Driver
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN)
that represents the target database.
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or
when no other alternative is available.
5.Database connection:
A Properties object holds a set of keyword-value pairs. It is used to pass driver properties
to the driver during a call to the getConnection() method.
try
{
Properties p = new Properties( );
FileInputStream f=new FileInputStream(“p1.txt”);
p.load(f);
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”, p);
}
catch(Exception e)
{
NOTE:just for reference-Following table lists down the popular JDBC driver names and
database URL.
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
jdbc:oracle:thin:@hostname:port
ORACLE oracle.jdbc.driver.OracleDriver
Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName
jdbc:sybase:Tds:hostname: port
Sybase com.sybase.jdbc.SybDriver
Number/databaseName
Connection conn = DriverManager.getConnection(URL, USER, PASS);
boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can
be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements
or when you need to use truly dynamic SQL.
ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method
when you expect to get a result set, as you would with a SELECT statement.
Program:
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”);
Statement s=c.createStatement();
ResultSet r=s.executeQuery(“Select *from emp”);
while(r.next())
{
String name=r.getString(1);
String usn=r.getString(2);
System.out.println(“name=”+name);
System.out.println(“USN=”+usn);
}
c.close();
}
catch(Exception e)
{
S.o.p(e);
The setXXX() methods bind values to the parameters, where XXX represents the Java
data type of the value you wish to bind to the input parameter.
o setXXX(int,string);
First parameter represent the column index and second parameter represent the values
that replace the ? mark in the query.
Next different execut methods of the preparedStatement object are called.
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”);
PreparedStatement p=c.PreaparedStatement(“select name from emp where usn=?”);
p.setSting(2, ”12cs001”);
Program:
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”);
CallableStatement p=c.CallableSatement(“Call lastOrderNumber(?)”);
p.registerOutParameter(1,TYPES.VARCHAR);
p.executeQuery();
String name=p.getString(1);
6. ResultSet
A ResultSet consists of records. Each records contains a set of columns.
A ResultSet can be of a certain type. The type determines some characteristics and abilities of the
ResultSet.
Scrollable ResultSet:
At the time of writing there are three ResultSet types:
1. ResultSet.TYPE_FORWARD_ONLY
2. ResultSet.TYPE_SCROLL_INSENSITIVE
3. ResultSet.TYPE_SCROLL_SENSITIVE
The default type is TYPE_FORWARD_ONLY
TYPE_FORWARD_ONLY means that the ResultSet can only be navigated forward. That is,
you can only move from row 1, to row 2, to row 3 etc. You cannot move backwards in
the ResultSet.
TYPE_SCROLL_INSENSITIVE means that the ResultSet can be navigated (scrolled) both
forward and backwards. You can also jump to a position relative to the current position,
Method Description
absolute() Moves the ResultSet to point at an absolute position. The position is a row
number passed as parameter to the absolute() method.
afterLast() Moves the ResultSet to point after the last row in the ResultSet.
beforeFirst() Moves the ResultSet to point before the first row in the ResultSet.
first() Moves the ResultSet to point at the first row in the ResultSet.
last() Moves the ResultSet to point at the last row in the ResultSet.
next() Moves the ResultSet to point at the next row in the ResultSet.
previous() Moves the ResultSet to point at the previous row in the ResultSet.
relative() Moves the ResultSet to point to a position relative to its current position. The
relative position is passed as a parameter to the relative method, and can be
both positive and negative.
PROGRAM:
import java.sql.*;
class A
{
A()
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”);
Statement s=c.createStatement(ResultSet.CONCUR_UPDATABLE);
ResultSet r=s.executeQuery(“Select *from emp where usn=2”);
r.update(1, ”Avinash”);
releaseSavePoint(String);-it realse the save point assing to the sql statement if and only
rollback();-if one of the sql statement is failed,then rollback() method is invoked and
control goes back to the fail sql statement for further execution.
Program:
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”);
Statement s=c.createStatement();
c.setAutoCommit(false);
8.Metadata:
Metadata is data about data. J2ee component can access metadata by using
DatabaseMetaData interface.
ResultSetMetaData interface
DatabaseMetaData interface:
The DatabaseMetaData interface is used to retrieve information about database,table,columns
and index amoung other information about dbms.
J2ee component retrives metadata about the database by calling getMetaData() method of the
connection interface object. The getMetaData() method return a DatabaseMetaData object that
contain information of database and components.
Most commonly used DatabaseMetaData interface methods as follows:
ResultSetMetaData interface:
ResultSetMetaData interface is used to retrieve the information by calling the getMetaData()
method of ResultSet interface.
Different methods in the ResultSetMetaData inetface are as follows:
getColunmCount()-returns the number of column available in the table
getColunmName(int)-returns the name of column specified by the column
number
getColunmTye(int)-returns the type of column specified by the column number
program:
import java.sql.*;
class A
{
A()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection c=DriverManager.getConnection(“JDBC:ODBC:CSB”);
Statement s=c.createStatement();
ResultSet r=s.executeQuery(“Select *from emp”);
ResultSetMetaData d=r.getMetaData();
System.out.println(d.getColunmName(1));
System.out.println(d.getColunmCount());
System.out.println(d.getColunmType(1));
}
c.close();
Data Types:
The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the
database. It uses a default mapping for most data types. The following table summarizes the default
JDBC data type that the Java data type is converted to, when you call the setXXX() method.
SQL JDBC/Java
VARCHAR String
CHAR String
LONGVARCHAR String
BIT boolean
NUMERIC java.math.BigDecimal
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT float
DOUBLE double
VARBINARY byte[ ]
BINARY byte[ ]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
CLOB java.sql.Clob
BLOB java.sql.Blob
SQLException Methods
An SQLException can occur both in the driver and the database. When such an exception occurs,
an object of type SQLException will be passed to the catch clause.
The passed SQLException object has the following methods available for retrieving additional
information about the exception −
Method Description
getErrorCode( ) Gets the error number associated with the exception.
Gets the JDBC driver's error message for an error,
getMessage( ) handled by the driver or gets the Oracle error number
and message for a database error.
Gets the XOPEN SQLstate string. For a JDBC driver
error, no useful information is returned from this
getSQLState( )
method. For a database error, the five-digit XOPEN
SQLstate code is returned. This method can return null.
getNextException( ) Gets the next Exception object in the exception chain.
Prints the current exception, or throwable, and it's
printStackTrace( )
backtrace to a standard error stream.
Prints this throwable and its backtrace to the print
printStackTrace(PrintStream s)
stream you specify.
Prints this throwable and it's backtrace to the print writer
printStackTrace(PrintWriter w)
you specify.