0% found this document useful (0 votes)
179 views

Chapter 4 Interacting With Database

The document discusses different types of database APIs and architectures for connecting Java applications to databases. It covers JDBC, ODBC, two-tier and three-tier architectures. JDBC is a specification that allows Java programs to connect to various databases via drivers. There are four types of JDBC drivers: Type 1 uses ODBC, Type 2 wraps a native API, Type 3 uses the database's network protocol with 100% Java code, and Type 4 relies on the database vendor's Java implementation.

Uploaded by

Atharv Kadam
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)
179 views

Chapter 4 Interacting With Database

The document discusses different types of database APIs and architectures for connecting Java applications to databases. It covers JDBC, ODBC, two-tier and three-tier architectures. JDBC is a specification that allows Java programs to connect to various databases via drivers. There are four types of JDBC drivers: Type 1 uses ODBC, Type 2 wraps a native API, Type 3 uses the database's network protocol with 100% Java code, and Type 4 relies on the database vendor's Java implementation.

Uploaded by

Atharv Kadam
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/ 103

Chapter 4

Interacting with Database


-by-
Prof. Bhandare P. S.
SVERI’s COE(Poly), Pandharpur
Syllabus
4.1 JDBC, ODBC, & Other APIS
JDBC two tier & three tier models

4.2 Connecting to Database


Driver Interface, Driver Manager class, Connection
Interface, Statement Interface, the java.sql.package
Establishing connection & retrieving information
Resultset interface.
Specific Objective
 To create database driven business
applications using the database API’S two
tier and three tier models and the Java.Sql
package
Java as Database Front End
 Java offers several benefits to the developer
creating a front-end application for a database
server.

 Java is ‘Write Once Run Everywhere’ language.

 This means that Java programs may be


deployed without recompilation on any
computer architectures and operating systems
that possesses a Java Virtual Machine.
 There are many industrial-strength DBMS
available in the market.

 These include Oracle DB2, Sybase and


many other popular brands.

 The challenge to Sun Microsystems faced in


the late 1990s was to develop a way for
Java developer to write a high level code
that accesses all popular DBMSs.
 The Sun Microsystems met the challenge in
1996 with the creation of JDBC driver for
JDBC API.

 Both were created out of necessity, because


until then Java wasn’t industrial strength
programming language since Java was
unable to access the DBMS.

 Java programmer could use high-level Java


data-objects defined in the JDBC API to
write a routine that interacted with the
DBMS.
Database client-server methodology
 Relational databases are the most common
DBMS.

A main characteristic of a relational


database is the absolute separation between
physical and logical data.

 Data is accessed through the associated


logical model to avoid supplying physical
storage locations and to reduce the
limitations imposed by using physical
information.
A language to handle, define, and control
data was developed at the IBM lab: SQL.

 SQL stands for Structured Query Language.


SQL is a query language that interacts with a
DBMS.

 It allows data access without supplying


physical access plans, data retrieval as sets of
records, and the performing of complex
computations on the data
Software Architectures
 The first generation of client-server architectures
is called two-tiered.

 It contains two active components: the client,


which requests data, and the server, which
delivers data.

 Basically, the application’s processing is done


separately for database queries and updates, and
for user interface presentations.

 Usually the network binds the back end to the


front end, although both tiers could be present on
the same hardware.
 For example, hundreds or thousands of
airline seat reservation applications can
connect to a central DBMS to request, insert,
or modify data.

 While the clients process the graphics and


data entry validation, the DBMS does all the
data processing.

 Actually, it is inadvisable to overload the


database engine with data processing that is
irrelevant to the server, thus some processing
usually also happens on the clients.
 The typical client-server architecture is
shown in Figure below:
 The two tiers are often called as Application
layer includes JDBC drivers, business logic
and user interfaces whereas second layer i.e.
Database layer consists of RDBMS server.

 Advantages:
◦ It is simple in design.
◦ Client-side scripting offloads work onto the client

 Drawbacks:
◦ Fat client.
◦ It is inflexible.
 Although the two-tiered architecture is
common, another design is starting to appear
more frequently.

 To avoid embedding the application’s logic


at both the database side and the client side,
a third software tier may be inserted.

 Inthree-tiered architectures, most of the


business logic is frozen in the middle tier.

 In this architecture, when the business


activity or business rules change, only the
middleware must be modified.
 Figure below illustrates the three-tier
architecture.
 Advantages:
◦ Flexible: It can change one part without affecting
others.
◦ It can connect to different databases without
changing code.
◦ Specialization: presentation / business logic / data
management.
◦ It can cache queries.
◦ It can implement proxies and firewalls.

 Drawbacks:
◦ Higher complexity
◦ Higher maintenance
◦ Lower network efficiency
◦ More parts to configure (and buy)
What is JDBC?
 The JDBC stands for Java Database
Connectivity.

 What is this JDBC besides a nifty acronym?

 It refers to several things, depending on


context:

 It’s a specification for using data sources in


Java applets and applications.

 It’s an API for using low-level JDBC drivers.


 It’san API for creating the low-level JDBC
drivers, which do the actual
connecting/transacting with data sources.

 It’s based on the X/Open SQL Call Level


Interface (CLI) that defines how client/server
interactions are implemented for database
systems.
 The JDBC is a package, much like other
Java packages such as java.awt.

 It’s not currently a part of the standard Java


Developer’s Kit (JDK) distribution, but it is
related to be included as a standard part of
the general Java API as the java.sql package.

 Soon after its official incorporation into the


JDK and Java API, it will also become a
standard package in Java-enabled Web
browsers, though there is no definite
timeframe for this inclusion.
 The exciting aspect of the JDBC is that the
drivers necessary for connection to their
respective databases do not require any pre-
installation on the clients: A JDBC driver can be
downloaded along with an applet!

 The JDBC project was started in January of


1996, and the specification was frozen in June
of 1996.

 Java soft sought the input of industry database


vendors so that the JDBC would be as widely
accepted as possible when it was ready for
release.
 The JDBC is heavily based on the ANSI SQL-92
standard, which specifies that a JDBC driver should
be SQL-92 entry-level compliant to be considered a
100 percent JDBC-compliant driver.

 This is not to say that a JDBC driver has to be written


for an SQL-92 database; a JDBC driver can be
written for a legacy database system and still function
perfectly.

 Even though the driver does not implement every


single SQL-92 function, it is still a JDBC driver.

 This flexibility will be a major selling point for


developers who are bound to legacy database systems
but who still want to extend their client applications.
The JDBC Structure
 The JDBC is two-dimensional.

 The reasoning for the split is to separate the


low-level programming from the high-level
application interface.

 The low-level programming is the JDBC driver.

 The idea is that database vendors and third-


party software vendors will supply pre-built
drivers for connecting to different databases.
 JDBC drivers are quite flexible: They can be
local data sources or remote database
servers.

 The implementation of the actual connection


to the data source/database is left entirely to
the JDBC driver.

 The structure of the JDBC includes these key
concepts:
 The goal of the JDBC is a DBMS
independent interface, a “generic SQL
database access framework,” and a uniform
interface to different data sources.

 The programmer writes only one database


interface; using JDBC, the program can
access any data source without recoding.
JDBC drivers
 Sun has defined four categories of JDBC
drivers.

 The categories delineate the differences in


architecture for the drivers.

 One difference between architectures lies in


whether a given driver is implemented in native
code or in Java code.

 Native code means whatever machine code is


supported by a particular hardware
configuration.
 For example, a driver may be written in C
and then compiled to run on a specific
hardware platform.

 Another difference lies in how the driver


makes the actual connection to the database.

 The four driver types are as follows:
Type 1 Driver: JDBC/ODBC Bridge
 This type uses bridge technology to connect
a Java client to a third-party API such as
Open DataBase Connectivity (ODBC).

 Sun's JDBC-ODBC bridge is an example of


a Type 1 driver.

 These code. This driver connects Java to a


Microsoft ODBC (Open Database
Connectivity) data source. drivers are
implemented using native
 TheJava 2 Software Development Kit from
Sun Microsystems, Inc. includes the JDBC-
to-ODBC bridge driver
(sun.jdbc.odbc.JdbcOdbcDriver).

 This driver typically requires the ODBC


driver to be installed on the client computer
and normally requires configuration of the
ODBC data source.
Type 2 Driver: Native API Driver
 This type of driver wraps a native API with Java classes.

 The Oracle Call Interface (OCI) driver is an example of


a Type 2 driver.

 Because a Type 2 driver is implemented using local


native code, it is expected to have better performance
than a pure Java driver.

 These drivers enable JDBC programs to use database-


specific APIs (normally written in C or C++) that allow
client programs to access databases via the Java Native
Interface.

 This driver type translates JDBC into database-specific


code.
Type 3 Driver: Network Protocol, Pure Java
Driver
 These drivers take JDBC requests and translate
them into a network protocol that is not
database specific.

 These requests are sent to a server, which


translates the database requests into a database-
specific protocol.

 This type of driver communicates using a


network protocol to a middle-tier server.

 The middle tier in turn communicates to the


database.
Type 4 Driver: Native Protocol, Pure
Java Driver
 These convert JDBC requests to database-
specific network protocols, so that Java
programs can connect directly to a database.

 Thistype of driver, written entirely in Java,


communicates directly with the database.
No local native code is required.

 Oracle's thin driver is an example of a Type 4


driver.
The JDBC API
 The JDBC API is contained in two packages
named java.sql and javax.sql.

 The java.sql package contains core Java objects


of JDBC API.

 There are two distinct layers within the JDBC


API: the application layer, which database-
application developers use and driver layer
which the drivers vendors implement.

 The connection between application and driver


layers is illustrated in figure below:
 There are four main interfaces that every
driver layer must implement and one class
that bridges the Application and driver
layers.

 The four interfaces are Driver, Connection,


Statement and ResultSet.

 The Driver interface implementation is


where the connection to the database is
made.

 In most applications, Driver is accessed


through DriverManager class.
The JDBC process
 Accessing JDBC / ODBC Bridge with the database

◦ Before actual performing the Java database


application, we associate the connection of
database source using JDBC – ODBC Bridge.
 The steps are as follows:
◦ 1. Go to Control Panel -> Administrative Tools -
> Data Sources.
◦ 2. Open Data Sources ODBC icon.
◦ 3.Select the tab with heading “User DSN”.

◦ 4.Click on ‘Add’ button.

◦ 5.Select the appropriate driver as per the database to


be used. (e.g. Microsoft ODBC driver for Oracle to
access Oracle Database

◦ 6.Click finish button and the corresponding ODBC


database setup window will appear.

◦ 7.Type DSN name and provide the required


information such as user name and password for the
database (.mdb files) of Microsoft Access Database
etc. and click on OK button.

◦ 8.Our DSN name will get appeared in user data


sources.
 There are six different steps to use JDBC in our
Java application program.

 These can be shown diagrammatically as below:


 1. Load the driver

 2. Define and establish the Connection

 3. Create a Statement object

 4. Execute a query

 5. Process the results

 6. Close the connection


Loading the JDBC driver
 The JDBC drivers must be loaded before the Java
application connects to the DBMS.

 The Class.forName() is used to load the JDBC


driver.

 The developer must write routine that loads the


JDBC / ODBC Bridge.

 The bridge driver called sun.jdbc.odbc.JdbcOdbcDriver. It


is done in following way:

 Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connect to the DBMS
 After loading the driver the application must
get connected to DBMS.

 For this we use DriverManager.getConnection()


method.

 The DriverManager is highest class in Java.sql


hierarchy and is responsible for managing
driver related information.

 he DriverManager.getConncetion() method is
passed the URL of the database and user ID and
password required by the database.
 The URL is the string object that contains the
driver name that is being accessed by the Java
program.

 The DriverManager.getConncetion() method


returns Connection interface that is used
throughout the process to reference the
database. The signature of this method is:

 Connection DriverManager.getConncetion(String url,


String userID, String password);

 Here, the URL format is specified as follows:

 <protocol>:<subprotocol>:<dsn-name>
 The ‘protocol’ is a JDBC protocol that is
used to read the URL.

 The ‘subprotocol’ is JDBC driver name and


‘dsn-name’ is the name of the database that
we provided while creating JDBC Bridge
though control panel.

 We use the following URL for our


application:

 jdbc:odbc:customer
 here, ‘customer’ is an example of DSN name
given to our database.

 The user name and password are also


provided at the time of creating DSN.

 It is not compulsory to provide the username


and password.

 For example:

 Conncetion con; con = DriverManager.getConnection


(“jdbc:odbc:customer”, “micro”, “pitch”);
Create Statement object
 The createStatement() method of
Connection interface is used to create the
Statement object which is then used to
execute the query.

 For example:

 Statement st = con.createStatement();
Execute the query
 The executeQuery() method of Statement
object is used execute and process the query
which returns the ResultSet object.

 ResultSet is the object which actually contains


the result returned by the query.

 For example:

 ResultSet rs = st.executeQuery (“select * from


customer”);

 Here, the ‘customer’ is neither database name


nor DSN name but it is a table name.
Process the results
 The ResultSet object is assigned the results received
from the DBMS after the query is processed.

 The ResultSet object consists of methods used to interact


with data that is returned by the DBMS to Java
application program.

 For example, the next() method is used to proceed


throughout the result set.

 It returns true, if the data is available in result set to read.

 The ResultSet also contains several getXxx( ) methods to


read the value from particular column of current row.
 String name;
 int age;
 do
 {
 name = rs.getString(“name”);
 age = rs.getInt(“age”);
 System.out.println(name+“=”+age);
 } while(rs.next());
Terminate the Connection
 The Connection to the DBMS is terminated by
using the close() method of the Connection
object once Java program has finished
accessing the DBMS.

 The close( ) method throws as exception if


problem is encountered when disengaging the
DBMS.

 For example:
 con.close();

 The close() method of Statement object is used


to close the statement object to stop the further
processing.
Statement object
 The Statement object is used whenever a
Java program needs to immediately execute
a query without first having query compiled.

 The Statement contains three different


methods depending upon the type of query
these will be used
1. executeQuery()
 This method returns the ResultSet object that
contains rows, columns and metadata that
represent data requested by the query. Its
signature is:

 ResultSet executeQuery(String query);

 Generally, this method is used to execute


only the ‘SELECT’ query of the SQL.
2. executeUpdate()
 This method is used to execute the queries that
contain INSERT, DELETE and UPDATE
statements.

 This method returns integer indicating the


number of rows that were updated by the query.
 Its signature is:
 int executeUpdate(String query);

 For example:

 int rows = st.executeUpdate("DELETE FROM


EMPLOYEES WHERE STATUS=0");
3. execute()
 It executes the given SQL statement, which may return multiple
results.

 In some (uncommon) situations, a single SQL statement may


return multiple result sets and/or update counts we must then use
the methods getResultSet( ) or getUpdateCount( ) to retrieve the
result, and getMoreResults( ) to move to any subsequent result(s).

 Signature is as follows:

 public boolean execute(String sql)

 For example:

 if(st.execute())
 rs = st.getResultSet();
PreparedStatement object
 A SQL query must be compiled before the DBMS processes the query.

 Compiling occurs after one of the Statement object’s execution method


is called.

 Compiling a query is an overhead that is acceptable if the query is called


once.

 However, compiling process can become an expensive overhead if the


query is executed several times by the same program during the same
session.

 A SQL query can be precompiled and executed by using the


PreparedStatement object. In such cases a query is created similar to
other queries.

 However, a question mark is given on the place for the value that is
inserted into the query after it is compiled. It is the value that changes
each time the query is executed.
 For doing this process, we need to construct the query
with question
 marks such as,

 “select * from nation where population > ?”

 Such type of the query is passed as the parameter to the


prepareStatement( ) method of the Connection object
which then returns the PreparedStatement object.

 For example:

 String query = “select * from nation where population


> ?”;

 PreparedStatement ps = prepareStatement(query);
 Once the PreparedStatement object is obtained, the setXxx( )
methods of it can be used to replace question mark with the value
passed to setXxx() method.

 There are a number of setXxx() methods available in

 PreparedStatement object, each of which specifies the data type


of value that is being passed to setXxx() method.

 For example, considering the above query again,

 ps.setInt(1, 100000);

 This method requires two parameters.

 First parameter is an integer that identifies position of the


question mark placeholder and second is the value that replaces
the question mark.
 If the query contains two question marks we
have to pass second value also using setXxx()
method.

 Now, we need to use appropriate execute


method depending upon type of the query
without any parameters.

 Such as,

 ResultSet rs = ps.executeQuery();

 This will generate the ResultSet object as the


execution of the query.
 The PreparedStatement contain all three execute methods but
without any parameters as given below:
 ResultSet executeQuery( )
 int executeUpdate( )
 boolean execute( )

 The setXxx( ) methods:

 void setBoolean(int index, boolean value);


 void setByte(int index, byte value);
 void setDate(int index, Date value);
 void setDouble(int index, double value);
 void setFloat(int index, float value);
 void setInt(int index, int value);
 void setLong(int index, long value);
 void setObject(int index, Object value);
 void setShort(int index, short value);
 void setString(int index, String value);
Java JDBC Tutorial
 JavaJDBC is a java API to connect and
execute query with the database.

 JDBC API uses jdbc drivers to connect with


the database.
Why use JDBC
 BeforeJDBC, ODBC API was the database
API to connect and execute query with the
database.

 But,ODBC API uses ODBC driver which is


written in C language (i.e. platform
dependent and unsecured).

 That is why Java has defined its own API


(JDBC API) that uses JDBC drivers (written
in Java language).
What is API
 API (Application programming interface) is
a document that contains description of all
the features of a product or software.

 It represents classes and interfaces that


software programs can follow to
communicate with each other.

 An API can be created for applications,


libraries, operating systems, etc
JDBC Driver
 JDBC Driver is a software component that
enables java application to interact with the
database.

 There are 4 types of JDBC drivers:


◦ JDBC-ODBC bridge driver
◦ Native-API driver (partially java driver)
◦ Network Protocol driver (fully java driver)
◦ Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
 The JDBC-ODBC bridge driver uses ODBC
driver to connect to the database.

 The JDBC-ODBC bridge driver converts


JDBC method calls into the ODBC function
calls.

 This is now discouraged because of thin


driver.
 Advantages:
◦ easy to use.
◦ can be easily connected to any database.
 Disadvantages:
◦ Performance degraded because JDBC method call is converted
into the ODBC function calls.
◦ The ODBC driver needs to be installed on the client machine.
2) Native-API driver
 The Native API driver uses the client-side
libraries of the database.
 The driver converts JDBC method calls into
native calls of the database API.
 It is not written entirely in java.
 Advantage:
◦ performance upgraded than JDBC-ODBC bridge
driver.

 Disadvantage:
◦ The Native driver needs to be installed on the
each client machine.
◦ The Vendor client library needs to be installed on
client machine.
3) Network Protocol driver
 The Network Protocol driver uses middleware (application
server) that converts JDBC calls directly or indirectly into
the vendor-specific database protocol.

 It is fully written in java.


 Advantage:
◦ No client side library is required because of
application server that can perform many tasks
like auditing, load balancing, logging etc.
 Disadvantages:
◦ Network support is required on client machine.
◦ Requires database-specific coding to be done in
the middle tier.
◦ Maintenance of Network Protocol driver becomes
costly because it requires database-specific coding
to be done in the middle tier.
4) Thin driver
 The thin driver converts JDBC calls directly into
the vendor-specific database protocol.

 That is why it is known as thin driver. It is fully


written in Java language.
 Advantage:
◦ Better performance than all other drivers.
◦ No software is required at client side or server
side.

 Disadvantage:
◦ Drivers depends on the Database.
5 Steps to connect to the
database in java
 There are 5 steps to connect any java
application with the database in java using
JDBC. They are as follows:

 Register the driver class


 Creating connection
 Creating statement
 Executing queries
 Closing connection
1) Register the driver class
 The forName() method of Class class is used to
register the driver class.

 This method is used to dynamically load the


driver class.

 Syntax of forName() method :

◦ public static void forName(String className)throws ClassNo


tFoundException

 Example to register the OracleDriver class


◦ Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
 The getConnection() method of DriverManager class
is used to establish connection with the database.

 Syntax of getConnection() method


◦ 1) public static Connection getConnection(String url)thr
ows SQLException

◦ 2) public static Connection getConnection(String url,Str


ing name,String password)
◦ throws SQLException

 Example to establish connection with the Oracle


database
◦ Connection con=DriverManager.getConnection(
◦ "jdbc:oracle:thin:@localhost:1521:xe","system","pass
word");
3) Create the Statement object
 The createStatement() method of
Connection interface is used to create
statement.

 The object of statement is responsible to


execute queries with the database.
 Syntax of createStatement() method
◦ public Statement createStatement()throws SQLException

 Example to create the statement object

 Statement stmt=con.createStatement();
4) Execute the query
 The executeQuery() method of Statement
interface is used to execute queries to the
database.

 This method returns the object of ResultSet


that can be used to get all the records of a
table.

 Syntax of executeQuery() method


◦ public ResultSet executeQuery(String sql)throws
SQLException
 Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
◦ while(rs.next())
◦{
◦ System.out.println(rs.getInt(1)+" "+rs.getStrin
g(2));
◦}
5) Close the connection object
 Byclosing connection object statement and
ResultSet will be closed automatically.

 The close() method of Connection interface


is used to close the connection.

 Syntax of close() method


◦ public void close()throws SQLException
 Example to close connection
◦ con.close();
Connectivity with Access without DSN
 import java.sql.*;
 class Test{
 public static void main(String ar[]){
 try{
 String url="jdbc:odbc:mydsn";
 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 Connection c=DriverManager.getConnection(url);
 Statement st=c.createStatement();
 ResultSet rs=st.executeQuery("select * from login");
 while(rs.next()){
 System.out.println(rs.getString(1));
 }
 }catch(Exception ee){System.out.println(ee);}
 }}
DriverManager class
 The DriverManager class acts as an
interface between user and drivers.

 Itkeeps track of the drivers that are available


and handles establishing a connection
between a database and the appropriate
driver.

 The DriverManager class maintains a list of


Driver classes that have registered
themselves by calling the method
DriverManager.registerDriver().
Commonly used methods of DriverManager class

1) public static void is used to register the given driver with


registerDriver(Driver driver): DriverManager.

2) public static void is used to deregister the given driver (drop the
deregisterDriver(Driver driver): driver from the list) with DriverManager.

3) public static Connection is used to establish the connection with the


getConnection(String url): specified url.

4) public static Connection


is used to establish the connection with the
getConnection(String url,String
specified url, username and password.
userName,String password):
Connection interface
A Connection is the session between java
application and database.

 The Connection interface is a factory of


Statement, PreparedStatement, and
DatabaseMetaData i.e. object of Connection
can be used to get the object of Statement
and DatabaseMetaData.

 The Connection interface provide many


methods for transaction management like
commit(), rollback() etc
Commonly used methods of Connection
interface:
 1) public Statement createStatement():
creates a statement object that can be used to
execute SQL queries.

 2) public Statement createStatement(int


resultSetType,int resultSetConcurrency):
Creates a Statement object that will generate
ResultSet objects with the given type and
concurrency.

 3) public void setAutoCommit(boolean


status): is used to set the commit status.By
default it is true.
 4) public void commit(): saves the changes
made since the previous commit/rollback
permanent.

 5) public void rollback():


Drops all changes
made since the previous commit/rollback.

 6) public void close():


closes the connection
and Releases a JDBC resources immediately.
Statement interface
 The Statement interface provides methods
to execute queries with the database.

 The statement interface is a factory of


ResultSet i.e. it provides factory method to
get the object of ResultSet.
Commonly used methods of Statement
interface:
 The important methods of Statement interface are as
follows:
 1) public ResultSet executeQuery(String sql): is used
to execute SELECT query. It returns the object of
ResultSet.

 2) public int executeUpdate(String sql): is used to


execute specified query, it may be create, drop, insert,
update, delete etc.

 3) public boolean execute(String sql): is used to execute


queries that may return multiple results.

 4) public int[] executeBatch(): is used to execute batch


of commands.
ResultSet interface
 The object of ResultSet maintains a cursor
pointing to a row of a table.

 Initially, cursor points to before the first row.

 But we can make this object to move forward


and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE
in createStatement(int,int) method as well as
we can make this object as updatable by:
Commonly used methods of ResultSet
interface
is used to move the cursor to the one row next from the current
1) public boolean next():
position.
is used to move the cursor to the one row previous from the current
2) public boolean previous():
position.

3) public boolean first(): is used to move the cursor to the first row in result set object.

4) public boolean last(): is used to move the cursor to the last row in result set object.

is used to move the cursor to the specified row number in the


5) public boolean absolute(int row):
ResultSet object.

is used to move the cursor to the relative row number in the


6) public boolean relative(int row):
ResultSet object, it may be positive or negative.

is used to return the data of specified column index of the current


7) public int getInt(int columnIndex):
row as int.
8) public int getInt(String is used to return the data of specified column name of the current
columnName): row as int.
9) public String getString(int is used to return the data of specified column index of the current
columnIndex): row as String.
10) public String getString(String is used to return the data of specified column name of the current
columnName): row as String.
Example of Scrollable ResultSet
 import java.sql.*;
 class FetchRecord{
 public static void main(String args[])throws Exception
 {
 Class.forName("oracle.jdbc.driver.OracleDriver");
 Connection con=DriverManager.getConnection("jdbc:oracle:th
in:@localhost:1521:xe","system","oracle");
 Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL
_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
 ResultSet rs=stmt.executeQuery("select * from emp765");
 //getting the record of 3rd row
 rs.absolute(3);
 System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.g
etString(3));
 con.close();
 }
 }
PreparedStatement interface
 The PreparedStatement interface is a subinterface of
Statement.

 It is used to execute parameterized query.

 Let's see the example of parameterized query:

 String sql="insert into emp values(?,?,?)";

 As you can see, we are passing parameter (?) for the


values.

 Its value will be set by calling the setter methods of


PreparedStatement.
Methods of PreparedStatement interface
Method Description

public void setInt(int paramIndex, int sets the integer value to the given
value) parameter index.

public void setString(int paramIndex, sets the String value to the given
String value) parameter index.

public void setFloat(int paramIndex, sets the float value to the given parameter
float value) index.

public void setDouble(int sets the double value to the given


paramIndex, double value) parameter index.

executes the query. It is used for create,


public int executeUpdate()
drop, insert, update, delete etc.

executes the select query. It returns an


public ResultSet executeQuery()
instance of ResultSet.
 import java.sql.*;
 class InsertPrepared{
 public static void main(String args[])
 {
 try{
 Class.forName("oracle.jdbc.driver.OracleDriver");
 Connection con=DriverManager.getConnection("jdbc:oracle:t
hin:@localhost:1521:xe","system","oracle");
 PreparedStatement stmt=con.prepareStatement("insert into E
mp 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 interface that updates
the record
 PreparedStatement stmt=con.prepareStatem
ent("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);

 int i=stmt.executeUpdate();
 System.out.println(i+" records updated");
PreparedStatement interface that deletes the
record

 PreparedStatement stmt=con.prepareState
ment("delete from emp where id=?");

 stmt.setInt(1,101);
 int i=stmt.executeUpdate();

 System.out.println(i+" records deleted");


PreparedStatement interface that
retrieve the records of a table
 PreparedStatement stmt=con.prepareStatem
ent("select * from emp");
 ResultSet rs=stmt.executeQuery();
 while(rs.next()){
 System.out.println(rs.getInt(1)+" "+rs.getSt
ring(2));
}
Java DatabaseMetaData interface
 DatabaseMetaData interface provides
methods to get meta data of a database such
as database product name, database product
version, driver name, name of total number
of tables, name of total number of views etc.
Commonly used methods of DatabaseMetaData
interface
 public String getDriverName()throws SQLException: it returns the
name of the JDBC driver.

 public String getDriverVersion()throws SQLException: it returns the


version number of the JDBC driver.

 public String getUserName()throws SQLException: it returns the


username of the database.

 public String getDatabaseProductName()throws SQLException: it


returns the product name of the database.

 public String getDatabaseProductVersion()throws SQLException: it


returns the product version of the database.

 public ResultSet getTables(String catalog, String schemaPattern,


String tableNamePattern, String[] types)throws SQLException: it
returns the description of the tables of the specified catalog. The table
type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM
etc.
Java Example to store image in the database
 import java.sql.*;
 import java.io.*;
 public class InsertImage {
 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 ps=con.prepareStatement("insert into imgtable val
ues(?,?)");
 ps.setString(1,"sonoo");
 FileInputStream fin=new FileInputStream("d:\\g.jpg");
 ps.setBinaryStream(2,fin,fin.available());
 int i=ps.executeUpdate();
 System.out.println(i+" records affected");
 con.close();
 }catch (Exception e) {e.printStackTrace();}
 }
 }
retrieve image from Oracle database
 import java.sql.*;
 import java.io.*;
 public class RetrieveImage {
 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 ps=con.prepareStatement("select * from imgtable");
 ResultSet rs=ps.executeQuery();
 if(rs.next()){//now on 1st row
 Blob b=rs.getBlob(2);//2 means 2nd column data
 byte barr[]=b.getBytes(1,(int)b.length());//1 means first image
 FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");
 fout.write(barr);
 fout.close();
 }//end of if
 System.out.println("ok");
 con.close();
 }catch (Exception e) {e.printStackTrace(); }
 }
 }
Java Example to store file in database
 import java.io.*;
 import java.sql.*;
 public class StoreFile
 {
 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 ps=con.prepareStatement(
 "insert into filetable values(?,?)");
 File f=new File("d:\\myfile.txt");
 FileReader fr=new FileReader(f);
 ps.setInt(1,101);
 ps.setCharacterStream(2,fr,(int)f.length());
 int i=ps.executeUpdate();
 System.out.println(i+" records affected");
 con.close();
 }catch (Exception e) {e.printStackTrace();}
}
}

You might also like