Module 5 21CS32
Module 5 21CS32
Module -5
JDBC Objects
JDBC API contains two packages. First package is called java.sql, second package is called
javax.sql which extends java.sql for advanced JDBC features.
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Or
Class.forName("oracle.jdbc.driver.OracleDriver");
import java.sql.*;
public class Test{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@
localhost:1521:","system","MANAGER");
The statement object is then used to execute a query and return result object that contain
response from the DBMS
Statement DataRequest;
ResultSet Results;
try {
String query=“select * from Customers”;
DataRequest=Database.createStatement();
Results= DataRequest.executeQuery(query);
}
Results= DataRequest.executeQuery(query);
do
{
Fname=Results.getString(Fname)
}
while(Results.next())
Database Connection
1. After the JDBC driver is successfully loaded and registered, the J2EE component must
connect to the database. The database must be associated with the JDBC driver.
2. The datasource that JDBC component will connect to is identified using the URL format.
The URL consists of three format.
These are jdbc which indicate jdbc protocol is used to read the URL.
<subprotocol> which is JDBC driver name.
<subname> which is the name of database.
3. Connection to the database is achieved by using one of three getConnection()
methods. It returns connection object otherwise returns SQLException
4. Three getConnection() method
getConnection(String url)
getConnection(String url, String pass, String user)
getConnection(String url, Properties prop)
5. getConnection(String url)
Sometimes the DBMS grant access to a database to anyone that time J2EE component
uses getConnection(url) method is used.
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Db=DriverManager.getConnection(“jdbc:oracle:thin:@
localhost:1521:”);
}
Timeout
Competition to use the same database is a common occurrence in the J2EE environment
and can lead to performance degradation of J2EE application. Database may not connect
immediately delayed response because database may not available. Rather than delayed waiting
timeJ2EE component can stop connection. After some time. This time can bet set with the
following method:
DriverManager.setLoginTimeout(int sec)
return the current timeout in seconds.
Connection Pool
Client needs frequent that needs to frequently interact with database must either open
connection and leave open connection during processing or open or close and reconnect
each time.
Leaving the connection may open might prevent another client from accessing the
database when DBS have limited no of connections. Connecting and reconnecting is time
consuming.
The release of JDBC 2.1 Standard extension API introduced concept on connection
pooling
A connection pool is a collection of database connection that are opened and loaded into
memory so these connections can be reused without reconnecting to the database.
DataSource interface to connect to the connection pool. connection pool is implemented
in application server.
There are two types of connection to the database 1.) Logical 2.) Physical
The following is code to connect to connection pool.
Context ctext= new IntialContext()
DataSource pool =(DataSource)
ctext.lookup(“java:comp/env/jdbc/pool”);
Connection db=pool.getConnection();
Example Program
import java.sql.*;
public class Test{
public static void main(String args[])
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:","system","MANAGER");
String query=”SELECT * FROM Customers where CustName = ?”;
PreparedStatement ps = Db.preparedStatement(query);
ps.setString(1,”123”);
ResultSet rs = ps.executeQuery(query);
}
Con.close();
catch(SQLException e)
{
System.err.println(e);
System.exit(1);
}
CallableStatement Object
The callableStatement object is used to call a stored procedure from within J2EE object. A
stored procedure is block of code and is identified by unique name. the code can bewritten in
PL/SQL.
Stored procedure is executed by invoking by the name of procedure.
The callableStatement uses three types of parameter when calling stored procedure. The
parameters are IN ,OUT,INOUT.
IN parameter contains data that needs to be passed to the stored procedure whose value is
assigned using setx() method.
OUT parameter contains value returned by stored procedure. The OUT parameter should be
registers by using registerOutParameter() method and then later retrieved by the J2EE
component using getx() method.
INOUT parameter is used to both pass information to the stored procedure and retrieve the
information from the procedure.
import java.sql.*;
public class Test{
public static void main(String args[])
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:","system","MANAGER");
stmt.setInt(1,id);
stmt.setString(2,n);
stmt.setString(3,j);
stmt.executeUpdate();
System.out.println("Want to insert more data
Yes/No");
String ans=sc.next();
//if user say no then insertion of data
stopped...
if(ans.equalsIgnoreCase("No"))
break;
}
//Connection is closed.....
con.close();
System.out.println("Successfully saved .....");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
Scrollable ResultSet
Until the release of JDBC 2.1 API , the virtual cursor can move only in forward directions.
But today the virtual cursor can be positioned at a specific row.
There are six methods to position the cursor at specific location in addition to next() in
scrollable result set. firs() ,last(), absolute(), relative(), previous(), and getRow().
first() position at first row.
last() position at last row.
previous() position at previous row.
absolute()… To the row specified in the absolute function
relative()………… move relative to current row. Positive and negative no can be
given.
Ex. relative(-4) … 4 position backward direction.
getRow() returns the no of current row.
There are three constants can be passed to the createStatement()
Default is TYPE_FORWARD_ONLY. Otherwise three constant can be passed to the
create statement 1.) TYPE_SCROLL_INSENSITIVE 2.) TYPE_SCROLL_SENSITIVE
3)TYPE_SCROLL makes cursor to move both direction.
INSENSITIVE makes changes made by J2EE component will not reflect. SENSITIVE means
changes by J2EE will reflect in the result set.
import java.sql.*;
public class Test{
public static void main(String args[])
FirstName = Results.getString(1);
LastName = Results.getString(2);
printrow = FirstName + “ “ + LastName;
System.out.println (printrow);
}while( Results.next());
Con.Cloase();
}
catch(SQLException err)
{
System.err.println("Error"+error);
System.exit(1);
}
Whatever the changes making will affect only in the result set not in the table. To update in the
table have to execute the DML (update, insert, delete) statements.
Statement DR=DB.createStatement();
DR.addBatch(query1);
DR.addBatch(query2);
int [] updated= DR.executeBatch();
Metadata
Metadata is data about data. MetaData is accessed by using the DatabaseMetaData interface.
This interface is used to return the meta data information about database.
Meta data is retrieved by using getMetaData() method of connection object.
Database metadata
The method used to retrieve meta data informations are
getDatabaseProductNAme()…returns the product name of database.
getUserNAme() returns the username
getURL() returns the URL of the databse.
getSchemas() returns all the schema name
getPrimaryKey() returns primary key
getTables() returns names of tables in the database
ResultSet Metadata
ResultSetMetaData rm = Result.getMeatData()
The method used to retrieve meta data information about result set are
getColumnCount() returns the number of columns contained in result set
SMALLINT Short
INTEGER Int
BIGINT Long
REAL Float
FLOAT Float
DOUBLE Double
VARBINARY byte[ ]
BINARY byte[ ]
DATE java.sql.Date
TIME java.sql.Time
SQLWarnings
it throws warnings related to connection from DBMS. getWarnings() method of connection
object retrieves t warnings. getNextWarnings() returns
subsequent warnings.
Data Truncation
Whenever data is lost due to truncation of the data value, a truncation exception is thrown.