Unit - 5: The Concept of JDBC
Unit - 5: The Concept of JDBC
Unit - 5: The Concept of JDBC
Unit -5
The Concept of JDBC:
1. Java was not considered industrial strength programming language since java was
unable to access the DBMS.
2. Each dbms has its own way to access the data storage. low level code required to
access oracle data storage need to be rewritten to access db2.
3. JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases
JDBC Architecture
JDBC Packages
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.
Explain the various steps of the JDBC process with code snippets.
1. Loading the JDBC driver
• The jdbc driver must be loaded before the J2EE compnet can be connected to
the database.
• Driver is loaded by calling the method and passing it the name of driver
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
• Once the driver is loaded , J2EE component must connect to the DBMS using
DriverManager.getConnection() method.
• It is highest class in hierarchy and is responsible for managing driver
information.
String url=”jdbc:odbc:JdbcOdbcDriver”;
String userId=”jim”
String password=”Keogh”;
Statement DatRequest;
Private Connection db;
try{
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Db=DriverManager.getConnection(url,userId,password);
}
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.
String url=” jdbc:odbc:JdbcOdbcDriver ”;
try{
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Db=DriverManager.getConnection(url);
}
• Database has limited access to the database to authorized user and require
J2EE to supply user id and password with request access to the database.
The this method is used.
try{
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Db=DriverManager.getConnection(url,userId,password);
}
Briefly explain the Statement object. Write program to call a stored procedure.(10)
Example Program
String url=”jdbc:odbc:JdbcOdbcDriver”;
String userId=”jim”
String password=”Keogh”;
Statement DatRequest;
Private Connection db;
ResultSet rs;
try{
String query=”UPDATE Customer set PAID=’Y’ where BALANCE =’0’;
DatRequest=Db.createStaement();
int n=DatRequest.executeUpdate(query);// returns no of rows updated
}catch(SQLException err)
{
System.err.println(“Error”);
System.exit(1);
}
Briefly explain the prepared statement object. Write program to call a stored
procedure.(10)
1. A SQL query must be compiled before DBMS processes the query. Query is
precompiled and executed using Prepared statements.
2. Question mark is placed as the value of the customer number. The value will be
inserted into the precompiled query later in the code.
3. Setxxx() is used to replace the question mark with the value passed to the setxxx()
method . xxx represents data type of the field.
Example if it is string then setString() is used.
4. It takes two arguments on is position of question mark and other is value to the filed.
5. This is referred as late binding.
String url=”jdbc:odbc:JdbcOdbcDriver”;
String userId=”jim”
String password=”Keogh”;
ResultSet rs;
}catch(SQLException err)
{
System.err.println(“Error”);
System.exit(1);
}
Briefly explain the callable statement object. Write program to call a stored procedure.(10)
1. The callableStatement object is used to call a stored procedure from with in J2EE
object. A stored procedure is block of code and is identified by unique name. the
code can bewritten in Transact-C ,PL/SQL.
3. The callableStatement uses three types of parameter when calling stored procedure.
The parameters are IN ,OUT,INOUT.
4. IN parameter contains data that needs to be passed to the stored procedure whose
value is assigned using setxxx() method.
6. INOUT parameter is used to both pass information to the stored procedure and
retrieve the information from the procedure.
BEGIN
END;
ResultSet
1. ResultSet object contain the methods that are used to copy data from
ResultSet into java collection object or variable for further processing.
2. Data in the ResultSet is logically organized into the virtual table for further
processing. Result set along with row and column it also contains meta data.
4. J2EE component should use the virtual cursor to each row and the use other
methods of the ResultSet to object to interact with the data stored in column of
the row.
5. The virtual cursor is positioned above the first row of data when the ResultSet
is returned by executeQuery () method.
6. The virtual cursor is moved to the first row with help of next() method of
ResultSet
7. Once virtual cursor is positioned getxxx() is used to return the data. Data type
of data is represents by xxx. It should match with column data type.
stmt = conn.createStatement();
String sql;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
1. 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.
2. 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().
3. first() ………… position at first row.
4. last()…………position at last row.
5. previous()……….position at previous row.
6. absolute()………. To the row specified in the absolute function
7. relative()………… move relative to current row. Positive and negative no can be given.
Ex. relative(-4) … 4 position backward direction.
8. getRow() ……… returns the no of current row.
9. There are three constants can be passed to the createStatement()
10. Default is TYPE_FORWARD_ONLY. Otherwise three constant can be passed to the
create statement 1.) TYPE_SCROLL_INSENSITIVE
2.) TYPE_SCROLL_SENSITIVE
11. 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.
Example code.
String sql=” select * from emp”;
DR=Db.createStatement(TYPE_SCROLL_INSENSITIVE);
RS= DR.executeQuery(sql);
12. Now we can use all the methods of ResultSet.
1. Rows contained in the result set is updatable similar to how rows in the table can
be updated. This is possible by sending CONCUR_UPDATABLE.
2. There are three ways in which result set can be changed. These are updating row ,
deleting a row, inserting a new row.
3. Update ResultSet
try{
String query= “select Fname, Lname from Customers
where Fname= ‘Mary’ and Lanme=’Smith’;
DataRequest= Db.
createStatement(ResultSet.CONCUR_UPDATABLE);
Rs= DataRequest.executeQuery(query);
Rs.updateString(1 ,”Jon”);
Rs.updateString(2 ,”Smith”);
Rs.insertRow();
}
6. 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.
10. Another way to combine sql statements into a single into a single transaction and then
execute the entire transaction .
11. To do this the addBatch() method of statement object. The addBatch() method receives a
SQL statement as a parameter and places the SQL statement in the batch.
12. executeBatch() method is called to execute the entire batch at the same time. It returns an
array that contains no of SQL statement that execute successfully.
String query1=”UPDATE Customers SET street =’ 5 th Main’” +
“Where Fname=’BoB’ “;
String query2=”UPDATE Customers SET street =’ 10 th Main’” +
“Where Fname=’Tom’ “;
Statement DR=DB.createStatement();
DR.addBatch(query1);
DR.addBatch(query2);
int [] updated= DR.executeBatch();
The method used to retrieve meta data information about result set are
10. getColumnCount() returns the number of columns contained in result set
SQL JDBC/Java
VARCHAR java.lang.String
CHAR java.lang.String
LONGVARCHAR java.lang.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
ARRAY java.sql.Array
REF java.sql.Ref
Exception handling allows you to handle exceptional conditions such as program-defined errors
in a controlled fashion.
2. JDBC Exception handling is very similar to Java Excpetion handling but for
JDBC.
SQLException
SQLWarnings
DataTruncation
• But ,the prepared statement has to verify its metadata in the database only once.
• But, if we want to execute a single SQL statement for the multiple number of times, it’ll go to
the PreparedStatement.
Java.sql.package include classes and interface to perform almost all JDBC operation such
as creating and executing SQL queries
University Questions