M 5
M 5
Every enterprise level application need to interact with DB for storing information.
✓Each DBMS defined its own low-level way to interact with programs to access
databases.
✓ This challenge was met with the creation of the JDBC driver and the JDBC API.
Sun Microsystems, inc. defined its own API for java called JDBC API.
The JDBC driver was not an actual a driver at all. It was a specification that
described the detail functionality of a JDBC driver.
DBMS manufacturers and third-party vendors were encouraged to build their own
JDBC drivers that conformed to Sun Microsystems, Inc.'s specifications.
Vendor JDBC drivers acts like translators that converts low level proprietary DBMS
messages to Low level messages understood by JDBC API and vice verse.
❖JDBC is a standard Java API for DB-independent
connectivity between java and wide range of
databases.
4. Return error messages (if query is not executed) also as per JDBC
specifications to JDBC driver.
• ODBC was the first DBMS Independent driver developed by Microsoft. JDBC was
created based on ODBC.
• Both JDBC and ODBC have similar driver specification and APIs.
• JDBC –to-ODBC driver receives msg from J2EE component that are according to JDBC
specification and translated into ODBC messages. Which are then translated into
message format understood by DBMS.
➢DBMS manufacturer provides both java/native code driver and API classes, so that
the J2EE component can generate platform specific code.
➢Drawback : Loss of portability of code because API classes of this driver wont work
with another DBMS.
➢They are completely implemented in java , hence called as pure java JDBC driver.
➢It uses middleware ( Application server) that converts JDBC calls into vendor specific
DB protocol. Hence called as Network protocol driver.
Type – 4 → JDBC driver
➢Similar to type-3 driver except that SQL are translated directly into format
required by DBMS.
JDBC packages
Java.sql → contains core java data objects of jdbc API. → part of J2SE
provides basics for connecting to DBMS
communicating data stored in DB.
Javax.sql → extends java.sql for advanced jdbc features like manage connection
pooling etc. → part of J2EE
JDBC process:
5 steps of the JDBC process to connect and interact between any java application
and DBMS with code snippets.
The JDBC driver must be loaded before the J2EE component can connect to the
DBMS. The class.forName() method is used to load the JDBC driver by passing
name of the driver to it.
syntax: : class.forName(driver_class_name);
Eg: class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Step 2 : connecting to DBMS
Once driver is loaded, the j2ee components must connect to the dbms using the static
method getConnection() of DriverManager class.
Returns connection object that is used through out the process, to reference a database
The java.sql.Connection interface is another member of the java . sql package that
manages communication between the driver and the J2EE component. It sends
statements to the DBMS for procesing.
➢ After jdbc driver is loaded and connection is successfully made with the database,
we can send a sql query to the dbms for processing.
➢ Must first create the statement object and then use this object to execute SQL
queries
1. The createStatement() method of connection interface is used to create the
statement object.
syntax : Statement stmt = con.createStatement();
2. This statement object is then used to execute query and return a resultset interface
object that contains the response from the dbms that includes one or more rows of
information required by J2EE component.
boolean executeQuery(String)
int executeUpdate(String) → where string is a SQL query to be executed
resultSet execute(string)
Code snippet:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con=DriverManager.getConnection(“JDBC:ODBC:CSB”);
Statement stmt = con .createStatement();
ResultSet rs = stmt. executeQuery(“Select *from emp”);
Once the ResultSet is received from the DBMS, the close() method is called to
terminate the statement. stmt.close();
Step 4 : processing the data returned by DBMS
➢ The java.sql.ResultSet object is assigned the results received from the DBMS after
processing the query.
➢ The java.sql.ResultSet object consists of methods used to interact with data returned
by DBMS.
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con=DriverManager.getConnection(“JDBC:ODBC:CSB”);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(“Select *from emp”);
while(rs.next())
{ String name=rs.getString(1);
System.out.println(“name=”+name);
}
con.close();
class InsertPrepared
import java.sql.*;
class A {
A()
{
try
{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con=DriverManager.getConnection(“JDBC:ODBC:CSB”);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(“Select *from stud”);
while(rs.next())
{ String name =rs.getString(1);
String usn=rs.getString(2);
System.out.println(“name=”+name);
System.out.println(“USN=”+usn);
}
c.close(); public stataic void main(String args[])
} {
catch(Exception e) A a1=new A();
{ System.out.println(e); } }}
}
Code snippet for inserting and updating records
Statement Objects
Once connection to the database is opened, the j2ee component creates and
sends a query to access data contained in database.
There are three types of statement object to execute the SQL query:
2. execute() method
• used when there may be multiple results returned.
3. executeUpdate() method
• used to execute queries that contain UPDATE and DELETE SQL statements,
which changes values in a row and removes a row respectively.
• returns an integer indicating the number of rows that were updated by the
query.
• used to SET, UPDATE, DELETE, and DDL statements
Prepared statement object.
✓SQL query can be precompiled and executed by using the PreparedStatement object.
OR
✓ Prepared statements are used to execute precompiled SQL Query and that can be
executed many times.
✓A question mark ? is used as a placeholder for a value that is inserted into the query
after the query is compiled .
import java.sql.*; Program to execute database transaction
OR
class InsertPrepared pgm to demonstrate insert statement
{ using prepared stmt
public static void main(String args[])
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
catch(Exception e){ System.out.println(e);
} }
PreparedStatement stmt=con.prepareStatement
("update emp set name=? where id=?");
stmt.setString(1,"Sonoo"); //1 specifies the first parameter in the query i.e. name
stmt.setInt(2,101);
code snippet to demonstrate update statement
int i =stmt.executeUpdate();
System.out.println( i +" records updated");
con.close();
Advantage
query is precompiled once and the setxxx() method called as needed to change the
specified values of the query without having to recompile the query.
Note : The precompiling is performed by the DBMS and is referred to as "late binding. "
CallableStatement
The CallableStatement object is used to call a stored procedure from within a J2EE object.
A stored procedure is a block of code and is identified by a unique name.
The type and style of code depends on the DMBS vendor and can be written in PL/ SQL,
Transact-SQL, C, or another programming language.
The stored procedure is executed by invoking the name of the stored procedure.
Example :
CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
2. OUT parameter → contains the value returned by the stored procedures, if any.
OUT parameter must be registered using the registerOutParameter()
method and later its value can be retrieved by the J2EE component using getxxx()
method.
It is a parameter whose value is supplied by the SQL statement it returns.
Once you have created the CallableStatement object , inut parameters are set and
output parameters are registered, you can execute it using one of the
execute() method.
cstmt.execute();
Note: preparedstatement objects provides only input parameters.
CallableStatement Example-1
a simple stored procedure that returns one value, first name of employee based on
provided id. ( Emp.sql)
Filename.java
a stored procedure named myProcedure to insert values in to this table as shown below:
import java.sql.*;
ResultSet maintains cursor/pointer which points to a single row of the query results using
which we can iterate and access database records one by one.
Initially, the cursor of ResultSet points to the position before the first row.
➢Data in a ResultSet object is logically organized virtual table consisting of rows and
columns.
➢In addition to data, the ResultSet object also contains metadata such as column names,
column size, and column data type
The method next() of ResultSet moves the cursor to the next row. It returns true if there is
further row otherwise it returns false.
Types of results sets
Based on the operations performed on resultsets , they are divided into 2 types:
• Readable resultset
• Updatable result set
Readable resultset
• We can only perform read operation on the result set by using getxxx()
methods .
• Cannot perform any updations on this resultset.
• By default resultset is readonly.
Updatable resultset:
•The resultsets that allows programmers to perform updation operations like
insert, update and delete are called updatable resultset.
Scroll sensitive Resultset -- After getting Resultset, if we perform any changes in DB and
if these changes are visible to resultset, then such resultsets are called scroll sensitive
resultsets. They are sensitive to DB updations.
Following methods of connection class to create statements are passed with desired
ResultSet constants to create required resultset.
RSTyp is a constant that indicates the type of a ResultSet object which can be any one
of the following
RSConcurrency is one of two ResultSet constants for specifying whether a result
set is read-only or updatable.
All the getter methods have two variants. 1st variant takes column index as
Parameter and 2nd variant accepts column name as Parameter.
Finally, we need to call close method on ResultSet instance so that all resources
are cleaned up properly. Eg : rs.close();
Navigational methods used by Scrollable Resultset
Description
Methods
public void beforeFirst() throws SQLException Moves the cursor just before the first row.
public void afterLast() throws SQLException Moves the cursor just after the last row.
public boolean first() throws SQLException Moves the cursor to the first row.
public void last() throws SQLException Moves the cursor to the last row.
public boolean absolute(int row) throws SQLException Movesthe cursor to the specified row.
updating row:
•Once the executeQuery() method of the statement object returns a result set,
updatexxx() method is used to assign the values to columns in the current row of
result set.
•It requires two parameters, name or number of the column and second parameter is
value to be changed .
•updateRow() method is called to update the values in the row(after all the
updatexxx() methods).
•This change occurs only in ResultSet. The corresponding row in the underlying table
remains unchanged.
Example:
try{
String query= “select Firstname, Lastname from Customers where Fname=
‘Mary’ and Lname=’Smith’;
Rs= stmt.executeQuery(query);
ResultSet rs = stmt.executeQuery(query);
rs.beforeFirst();
rs.absolute(3);
rs.deleteRow();
rs.beforeFirst();
while (rs.next())
{
System.out.print("id: "+rs.getInt(1)+", ");
System.out.print("First name: "+rs.getString(2)+", ");
System.out.print("Year of birth: "+rs.getDate(4)+", ");
System.out.print("Country: "+rs.getString(6)+", ");
}
}
}
Insert Row into result set
❖Inserting a row into the ResultSet uses the same technique similar to updating the
ResultSet.
❖Once the executeQuery() method of the statement object returns a result set.
updatexxx() methods are used to assign values to the row that you want to insert.
❖ updatexxx() requires two parameters, where first is column name or column number.
Second parameter is the value to insert into that column.
❖ insertRow() method is called after all the updatexxx() methods are called, to insert a
new row into resultset and also into the database.
try{
String query= “select * from Emp’;
stmt = con. createStatement(ResultSet.CONCUR_UPDATABLE);
rs= stmt.executeQuery(query);
rs.updateString("name", "Venkat");
rs.updateString("position", "DBA");
rs.updateDouble("salary", 925.0);
rs.insertRow();
}
Transaction processing
2. Transaction is not completed until the J2EE component calls the commit() method
of the connection object. All SQL statements executed prior to the call to commit()
method can be rolled back. once the commit() method is called, none of the SQL
statements can be rolled back.
3. Commit() method was automatically called in the program. DBMS has AutoCommit
feature that is by default set to true.
commit();-once all sql statement are executed successfully, rollback is not possible.
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.
Code snippet to execute DB transaction.
try {
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.executeUpdate(“insert into emp values(106,20,’rita’,’tez’)”);
//submit a malformed SQL statement that fails
stmt.executeUpdate(“insert in emp values(107,25,’sita’,’singh’)”);
// ifthere is no error
con.commit();
stmt.close();
con.close();
}
Catch(SQLException se)
{
// if error
con.rollback();
}
Exceptions
1. SQLExceptions
2. SQLWarnings
3. DataTruncation.
1. SQLExceptions commonly reflect a SQL syntax error in the query and are thrown by
many of the methods contained in the java.sql package.
An SQL exception can occur both in driver as well as in database.
This exception is most commonly caused by
• connectivity issues with the database.
• subtle coding errors like trying to access an object that's been closed. For
example, you try to roll back a transaction in a catch clause and don't check first if
the database connection is still valid.
methods of the SQLExceptions object :
getNextException() - returns details about the SQL error or a null if the last exception
was retrieved.
getErrorCode() -- to retrieve vendor-specific error codes.
getNextException – gets the next exception object in the exception chain.
2. The SQLWarning throws warnings received by the Connection from the DBMS.
The getWarnings() method of the Connection object retrieves the warning and
subsequent warnings.