0% found this document useful (0 votes)
33 views45 pages

M 5

Uploaded by

hitharth08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views45 pages

M 5

Uploaded by

hitharth08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

JDBC

Every enterprise level application need to interact with DB for storing information.

Every J2EE application saves, retrieves, and manipulates information stored in a


database using web services provided by a J2EE component.

Various DBMS commercially available in market


Oracle
MySQL
SyBase
DB2 are the popular brands

✓Major obstacles for sun microsystems, inc. was a language barrier.

✓Each DBMS defined its own low-level way to interact with programs to access
databases.

✓Low-level code written to communicate with an oracle database might need to be


rewritten to access a db2 database.

✓ 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.

❖Java APIs are used to connect, communicate and


execute query with DB through JDBC drivers.

❖JDBC driver plays an important role in JDBC


architecture in processing SQL request and
generate results.

❖Java applications that wants to communicate


with DB are programmed using JDBC APIs.

❖Driver Manager uses specific drivers to connect


with specific DBs.

❖JDBC drivers is a software component (J2EE


component) that enables java application to
interact with DB.
Responsibilities of JDBC Drivers

1. Open connection between DBMS and J2EE component

2. Translates low level equivalents of SQL statements sent by J2EE


component into messages processed by DBMS.

3. Once after the query is processed by underlying DB, return the


data/records to JDBC drivers as per JDBC specifications.

4. Return error messages (if query is not executed) also as per JDBC
specifications to JDBC driver.

5. Provide transaction management routines as per JDBC specification

6. Close the connection between DBMS and JDBC component.


JDBC driver types:
Group of derivers addresses a specific need for communicating with various DBMSs.

Type – 1 → JDBC –to-ODBC 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.

• Hence also called as JDBC/ODBC bridge.

• Extra translation might negatively impact the performance.


• All DBs support ODBC access.
• Recommended for experimental use or when no alternatives are available.
• Has to be installed on client machine.
Type – 2 driver → Java / Native code driver

➢Uses java classes to generate platform specific code

➢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.

➢Also called as partial JDBC driver.

Type – 3 → JDBC driver → (pure Java driver for middleware)

➢Most commonly used JDBC driver.


➢Converts SQL queries into JDBC formatted statements
➢They are then translated into format required by 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

➢Also known as Type -4 DB protocol

➢Similar to type-3 driver except that SQL are translated directly into format
required by DBMS.

➢SQL queries need not be converted to JDBC formatted statements. Therefore it is


fastest way to communicate SQL queries to DBMS. So called as thin driver.

➢Better performance than other drivers

➢But drivers depends on DB.

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.

1. Loading the jdbc drivers


2. Connecting to dbms
3. Creating and executing statements
4. Processing data returned by dbms
5. Terminating the connection with the dbms

Step 1 : Loading the jdbc drivers (Register the driver Class)

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.

Java.sql.DriverManager class is the highest class in java.sql heirarchy and is also


responsible for managing driver information.

Arguments passed to getConnection() method


• URL → the string object that contains the driver name and databse name that is
being accessed by the j2ee components.
• userID , password → (optional) passed if required by DBMS

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.

Syntax : Connection con = DriverManager.getConnection(URL, USER, PASS);


The popular JDBC driver names and database URL.

RDBMS JDBC driver name URL format


MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:portNumber:


databaseName

DB2 com.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:portNumber/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: portNumber/


databaseName
MS Access sun.jdbc.odbc.JdbcOdbcDriver jdbc : odbc : databaseName

URL → always starts with jdbc:


Hostname → home/IP address of the machine that is running database
Port number → port on which database is running on system

Eg 1: Connection con = DriverManager . getConnection


(“jdbc:mysql://localhost/customer”, “root”, “nbuser”);

Eg 1: Connection con = DriverManager . getConnection(“jdbc:odbc:emp”, “scott”, “tiger”);


Step 3 : create and execute SQL statement

➢ 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();

The return is the Statement interface.

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.

eg : ResultSet rs = stmt. executeQuery(“Select *from emp”);


The different methods are used to execute the query are as follows:

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);
}

➢ ResultSet pointer is positioned at the first row in the ResultSet initially.


➢ next() method returns true if a row of data is present in resultset, false indicates that
no rows are present in the ResultSet.
➢ The getString() → either column name or column number is passed as a parameter
whose content needs to be extracted, and it is returned in string form.
Step 4 : Terminate the connection to DBMS

The connection to the dbms is terminated by the close() method on connection


interface when once the j2ee component is finished accessing the dbms.

con.close();

• Close() method may throw an exception if any problem occurs during


disconnecting the DBMS.

• Closing the DB connection automatically closes the resultset. Therefore it is


better to close the resultset explicitly before closing the connection.
program to retrieve the data from the database OR pgm to execute database transaction

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:

Statement object → which executes a query immediately


preparedStatemnt object → used to execute a compiled query
callableStatement object → used to execute store procedures.
Statement Object

Used whenever a J2EE component needs to immediately execute a query without


precompiling. The createStatement() method of connection interface is used to create
the statement object.
syntax : Statement stmt = con.createStatement();

The Statement object contains


1. executeQuery() method
• passed with query as an argument.
• The query is then transmitted to the DBMS for processing.
• The executeQuery() method returns one ResultSet object that contains rows,
columns, and metadata that represent data requested by query.
• The ResultSet object also contains methods that are used to manipulate data in the
ResultSet

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.

✓A SQL query must be compiled before DBMS processes the query.


✓Compiling a query can become an expensive overead if the query is executed several times
by the same instance of the J2EE component during the same session.

✓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.

✓The PreparedStatement interface extends the Statement interface.

✓This statement have added functionality and flexibility of supplying arguments


dynamically. It is used to execute parameterized query.
✓the query is constructed in same way as they are created for statement object, but ? is
used as a placeholder instead of value in the query. It is this value that changes each time
the query is executed.

PreparedStatement ps=con. PreparedStatement(“select name from emp where usn=?”);

✓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");

PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");


stmt.setInt(1,101); //1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

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();

PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");


stmt.setInt(1,101);
 code snippet to demonstrate delete statement
int i=stmt.executeUpdate();
System.out.println( i+" records deleted");
con.close();

code snippet PreparedStatement stmt=con.prepareStatement("select * from emp");


to ResultSet rs=stmt.executeQuery();
demonstrate while(rs.next())
select → System.out.println(rs.getInt(1)+" "+rs.getString(2));
statement
con.close();
The setxxx() method of the PreparedStatement object is used to replace the
question mark with the value passed to the setxxx() method. The setxxx() takes two
parameters.
▪ The first parameter is an integer that identifies the position of the question mark
placeholder
▪ the second parameter is the value that replaces the question mark placeholder.

Various forms of setxxx() are :

public void setInt(int paramIndex, int)


public void setString(int paramIndex, String)
public void setFloat(int paramIndex, float)
public void setDouble(int paramIndex, double value)

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 JDBC CallableStatement interface extends PreparedStatement interface and hence


these are also precompiled.

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.

The prepareCall() method of Connection interface returns the instance of


CallableStatement.
Syntax : public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

Example :
CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

It calls the procedure myprocedure that receives 2 arguments.


The CallableStatement object uses three types of parameters when calling a stored
procedure.
1. IN parameter → contains any data that needs to be passed to the stored
procedure and whose value is assigned using the setxxx() method. It is a parameter
whose value is unknown when the SQL statement is created.

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.

3. INOUT parameter → is a single parameter that is used to both pass information


to the stored procedure and retrieve information from a stored procedure.
we can bind variables with its value using setXXX() method and
retrieve values with the getXXX() methods

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)

CREATE OR REPLACE getEmpName (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))


BEGIN
SELECT firstname INTO EMP_FIRST FROM Emp WHERE ID = EMP_ID;
END

Filename.java

Public class JDBCCallableStatementExample


{
static final String DB_URL = "jdbc:mysql://localhost/”;
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "{call getEmpName (?, ?)}";
public static void main(String[] args)
{
Class.forName(“com.mysql.jdbc.Driver”);
Connection con = DriverManager.getConnection(DB_URL, USER, PASS);

CallableStatement stmt = con.prepareCall(QUERY);

// Bind values into the parameters.


stmt.setInt(1, 102);
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
System.out.println("Executing stored procedure..." );
stmt.execute();

//Retrieve employee name with getXXX method


String empName = stmt.getString(2);
System.out.println("Emp Name with ID: 102 is " + empName);
}
stmt.close(); con.close();
}
CallableStatement Example-2

a stored procedure named myProcedure to insert values in to this table as shown below:

Create procedure myProcedure


(IN name VARCHAR(30), IN sal INT, IN loc VARCHAR(45))
-> BEGIN
-> INSERT INTO Employee(Name, Salary, Location) VALUES (name, sal, loc);
-> END

import java.sql.*;

public class CallableStatementExample {


public static void main(String args[]) throws SQLException
{
//Registering the Driver
Class.forName(“com.mysql.jdbc.Driver”);
cstmt.setString(1, "Raghav");
cstmt.setInt(2, 3000);
Connection con = DriverManager.
cstmt.setString(3, "Hyderabad");
getConnection(jdbc:mysql://localhost/testdb”, "root", "password");
cstmt.setString(1, "Kalyan");
cstmt.setInt(2, 4000);
CallableStatement cstmt = con.prepareCall
cstmt.setString(3, "Vishakhapatnam");
("{call myProcedure( ? , ? , ?) } ");
cstmt.setString(1, "Rukmini");
cstmt.setInt(2, 5000);
cstmt.setString(3, "Delhi");
cstmt.execute();
System.out.println("Rows inserted ....");
}}
ResultSet
A ResultSet Object is used to access query results retrieved from the databases.

ResultSet can be obtained by executing SQL Query using Statement,


PreparedStatement or CallableStatement.

ResultSet can also be used to update data.

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.

Based on the cursor movements Resultsets are divided into 2 types:


• Forward only(Unscrollable) Resultset
• Scrollable Result set
Forward only(Unscrollable) Resultset :
• Allows resultset cursor/pointer can move only in forward direction from first row to
last row sequentially.
• By default every resultset is forward only.
• Uses next()method – access the next record of resultset

Scrollable Result set


Allows the cursor to move in both forward and backward directions.
Allows the cursor to move to random position and position relative to current position
using navigational methods.

There are 2 types of Scrollable Result sets:

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.

Scroll Insensitive Resultset – After getting Resultset, if we perform any changes in DB


and if these changes are not reflecting( or not visible) on the resultset, then such
resultsets are called scroll insensitive RSs. They are insensitive to DB updations.
Creating required Resultset

Following methods of connection class to create statements are passed with desired
ResultSet constants to create required resultset.

statement.createStatement(int RSType, int RSConcurrency);


statement.prepareStatement(String SQL, int RSType, int RSConcurrency);
statement.prepareCall(String sql, int RSType, int RSConcurrency);

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.

Eg : Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet. CONCUR_UPDATABLE);


The ResultSet object contains 3 categories of methods :
Navigational methods − Used to move the cursor around.
Get methods − Used to retrieve the data in the columns of the current row
being pointed by the cursor.
Update methods − Used to update the data in the columns of the current row.

getter methods provided by ResultSet to retrieve the data are :


getInt() eg: Integer empId = rs.getInt(1);
getString() eg : String firstName = rs.getString(2);
getDate() eg : String dob = rs.getString(3);

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.

Moves the cursor the given number of rows


public boolean relative(int row) throws SQLException forward or backward, from where it is currently
pointing.
Moves the cursor to the previous row.
public boolean previous() throws
This method returns false if the previous
SQLException
row is off the result set.

Moves the cursor to the next row. This


public boolean next() throws
method returns false if there are no more
SQLException
rows in the result set.

Returns the row number that the cursor is


public int getRow() throws SQLException
pointing to.

Moves the cursor to a special row in the


public void moveToInsertRow() throws result set that can be used to insert a new
SQLException row into the database. The current cursor
location is remembered.

Moves the cursor back to the current row


public void moveToCurrentRow() throws
if the cursor is currently at the insert row;
SQLException
otherwise, this method does nothing
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.TPYE_SCROLL_SENSITIVE);
ResultSet r=s.executeQuery(“Select *from emp”);
While(r.next())
{ String name=r.getString(1); r.relative(2);
String usn=r.getString(2); System.out.println(r.getString(1));
System.out.println(“name=”+name); r.relative(-2);
System.out.println(“USN=”+usn); System.out.println(r.getString(1));
} r.close(); s.close();
r.first(); c.close();
System.out.println(r.getString(1)); }
r.last(); catch(Exception e)
System.out.println(r.getString(1)); { S.o.p(e); }
r.previous(); }
System.out.println(r.getString(1)); public static void main(String ar[])
r.absolute(2);
System.out.println(r.getString(1)); { A a1=new A(); }
}
Updatable ResultSet
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 to the createStatement()
method of the Connection object
There are three ways in which result set can be changed. These are updating row ,
deleting a row, inserting a new 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’;

stmt= con. createStatement(ResultSet.CONCUR_UPDATABLE);

Rs= stmt.executeQuery(query);

Rs.updateString(“LastName”,”jon”); // mary smith is changed to mary jon


Rs.updateRow();
}

Delete row in result set

❖ The deleteRow() method is used to remove a row from a ResultSet.


❖First, use absolute() method to navigate the virtual cursor to the row to be deleted.
❖Then call deleteRow(), to delete the current row.
❖This also deletes it from the underlying database.
❖rs.deleteRow(0) → passing 0(zero) also deletes the current row.
import java.sql.*;

public class ResultSet_DeletingRow {


public static void main(String args[])throws Exception
{
Class.forName(“com.mysql.jdbc.Driver”);

Connection con = DriverManager.getConnection


("jdbc:mysql://localhost/mydatabase”, "root", "pw");

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_UPDATABLE);

String query = "select * from Cricket";

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

1. A transaction may consists of a set of SQL statements, each of which must be


successfully completed for the transaction to be completed. If one SQL stmt fails,
the entire transaction is fail. If one of sql is failed, the sql statement that is executed
successfully upto the point in the transaction must be rolled back

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.

4. If the J2EE component is processing a transaction, the AutoCommit feature must be


deactivate by calling the setAutoCommit() method and passing it a false parameter.

5. Once the transaction is completed, the setAutoCommit() method is called again- by


passing it a true parameter, reactivating the AutoCommit feature.
Different methods used in Transaction processing are:

setAutoCommit(boolean) - setAutoCommit() pass the parameter as false intially


once all the transcation is completed. As soon as it invokes the commit() ,the
setAutoCommit() method is set as true.

setSavePoint(String);-set the save point to the sql statement .

releaseSavePoint(String);-it realses the save point assigned to the sql statement if


and only if all sql statement are executed successfully.

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.

Class. forName ( sun . jdbc . odbc . JdbcOdbcDriver } ;


Connection con = DriverManager . getConnection("jdbc: odbc :Customerinformation “);

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

There are three kinds of exceptions thrown by JDBC methods.

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.

3. Whenever data is lost due to truncation of the data value, a DataTrunction


exception is thrown.

You might also like