SlideShare uma empresa Scribd logo
1 de 49
JAVA DATABASE CONNECTIVITY
A vendor neutral way to talk to database

By
Atul Saurabh
Assist. Professor
Babaria Institute of Technology
THE DATABASE
A database is an organized collection of data.
-Wikipedia
a)

A file contains data in sequential form. Whenever we need
to retrieve data from a file, we need to traverse the file
character by character.

b)

There is no natural way to establish relation between file
even though we can distribute data in different files.

c)

There is no effective way to check whether there is any
redundancy in the file.

d)

There is no effective way to check the integrity of the data
in a file.
FORMS OF DATABASES
On the basis of organization of data, database appears
in different forms
a)

Relational Database : The data is organized in form
of relations or tables. E.g. Oracle, MySQL, SyBase,
Postgres etc.

b)

Hierarchal Database : The data is organized in
some tree form. E.g. XML, LDAP ect.

c)

Object Oriented Database : The data is
encapsulated in form of object. Each object
represent a row from some table in other kind of
database. E.g. Java Persistence API, Hibernate etc.
TALKING TO THE DATABASE
Each database vendor follows their own protocols for
managing data inside database. Though the same
syntax i.e. SQL is followed by every database vendor,
their internal representation of data, i.e. datatype, is
different. As for example MySQL uses float for floating
type number but Oracle uses number(m,n) for the
same.
Programming language like Java provides its own
syntax and datatypes.
These diversities simply put a requirement of a layer
which translate programming language representation
into vendor specific representation. This layer is
commonly known as database driver.
PREREQUISITES FOR DATABASE CONNECTION
Whenever a database is connected through some
programming language following information is
required:
1)

The driver class

2)

Authentication credentials for database engine

3)

The URL to locate the database.
STEPS TO CONNECT DATABASE THROUGH
JAVA
1)

Installation of vendor specific driver : Normally
drivers comes in form of JAR file. Here are the
names of some drivers
a) ORACLE : oracle.jdbc.driver.OracleDriver
b) MySQL : com.mysql.jdbc.Driver
c) Postgres : org.postgresql.Driver
d) ODBC

: sun.jdbc.odbc.JdbcOdbcDriver

There are three ways to install JDBC driver.

i) Create a lib folder inside the project folder and
place the JDBC driver JAR file inside lib and set
classpath using manifest file.
ii) CLASSPATH : set class path. Follow the steps :

Create any directory inside the system say in D: drive
create a directory with name library. Put the JAR file
inside this folder. Let the name of jar is mysqlconnector-java-5.0.8-bin.jar. Now
Go to

My Computer
|--Properties
|---Advanced System Setting
|------Environmental Variable
|---- User Variable
|-----New
The following windows appears :
In variable name write
CLASSPATH
In variable value write

D:library mysql-connector-java-5.0.8-bin.jar;

.

(Mind the last . (dot) after semi-colon)
iii)
Place
your
JAR
%JAVA_HOME%/jre/lib/ext directory.

file

If ODBC driver is used then no need to install the
driver. Skip this step

inside
2) Instantiate the driver : To instantiate the driver
following code can be used
class DatabaseConnection
{
public void makeConnection()
{
try
{
String
driverClass=“sun.jdbc.odbc.JdbcOdbcDriver”
Class.forName(driverClass);
}
catch(ClassNotFoundException e)
{
Logger.getLogger(DatabaseConnection.class.getName()).l
og(Logger.SEVER,”The Driver Class Is Not Located”,e);
}
}
3) Establish the connection : Use DriverManager to establish the
connection:
public class DatabaseConnection
{
public void makeConnection()
{
try {
String driverClass=“sun.jdbc.odbc.JdbcOdbcDriver”
String username=“”;
String passwd=“”;

String url=“jdbc:odbc:dsn”;

Class.forName(driverClass);
Connection c=DriverManager.getConnection(url,username,passwd);
if(!c.isClosed())
System.out.println(“Connection established”);
}
catch(ClassNotFoundException e) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Logger.SEVER,
”The Driver Class Is Not Located”,e);
}
catch(SQLException sqle){
Logger.getLogger(DatabaseConnection.class.getName()).log(Logger.SEVER,
”Unable To Connect”,sqle);
}
}
}
CREATING A DSN
DSN stands for Data Source Name. It is required only if
we are using ODBC driver. To create a DSN use the
following steps :
Go To

Control Panel
|----Administrative Tool
|--- Data Source
And create a System DSN by supplying the DSN name
and selecting the database.
ARCHITECTURE OF JDBC
TYPES OF JDBC DRIVERS
Type 1: JDBC-ODBC Bridge Driver:
In a Type 1 driver, a JDBC bridge is used to access ODBC
drivers installed on each client machine. Using ODBC
requires configuring on your system a Data Source Name
(DSN) that represents the target database.
Type 2: JDBC-Native API:

In a Type 2 driver, JDBC API calls are converted into
native C/C++ API calls which are unique to the database.
These drivers typically provided by the database vendors
and used in the same manner as the JDBC-ODBC Bridge,
the vendor-specific driver must be installed on each
client machine.
Type 3: JDBC-Net pure Java :

In a Type 3 driver, a three-tier approach is used to
accessing databases. The JDBC clients use standard
network sockets to communicate with an middleware
application server. The socket information is then
translated by the middleware application server into the
call format required by the DBMS, and forwarded to the
database server.
Type 4: 100% pure Java:

In a Type 4 driver, a pure Java-based driver that
communicates directly with vendor's database through
socket connection. This is the highest performance driver
available for the database and is usually provided by the
vendor itself.
SQL DATA TYPE AND CORRESPONDING
JAVA TYPES
Sl. No.

SQL Data Type

Java Data Type

1

INTEGER, INT

int

2

SMALLINT

short

3

NUMERIC(m,n),
DECIMAL(m,n),
DEC(m,n)

java.math.BigDecimal

4

FLOAT(n)

double

5

REAL

float

6

CHARACTER(n),
CHAR(n)

String

7

VARCHAR(n)

String
Sl. No.

SQL Data Type

Java Data Type

8

BOOLEAN

Boolean

9

DATE

java.sql.Date

10

TIME

java.sql.Time

11

TIMESTAMP

java.sql.Timestamp

12

BLOB

java.sql.Blob

13

CLOB

java.sql.Clob

14

ARRAY

java.sql.Array
EXECUTING SQL QUERY
In native SQL there are two types of queries
a)

The query which changes the values in one or more
rows possibly by creating or deleting rows. E.g.
INSERT, UPDATE, DELETE and ALTER.

b)

The query which simply returns the projection of one
or more tables. E.g. SELECT.

Whenever we execute query (a) then the query always
returns us how many rows get affected.
Whenever we execute query (b) we get a snapshot of
subset original table(s). This snapshot is commonly
known as ResultSet.
The java.sql.Connection
The Connection object represents a connection to the
database.
i) Statement createStatement() : This method is used to
get the Statement object
The java.sql.Statement
The Statement object is used to execute a native SQL
queries.
i)

ResultSet executeQuery(String query) : This method
is used to execute query (b).

ii)

int executeUpdate(String query) : Used to execute
query (a).

iii)

Int getUpdateCount() : Returns the number of records
affected by previous update query.
The java.sql.ResultSet
The ResultSet is a snapshot of subset of original tables(s) .
A ResultSet is always provided by a cursor.
Initially cursor is pointed outside the table. We can
visualize ResultSet as follows

Col1

Col2

….

Coln

R01

R02

….

R0n

R11

R12

....

R1n

R21

R22

….

R2n
i)

boolean next() : This method moves the cursor one
row downward and returns true if there is any row
available below the cursor.

ii)

Xxx getXxx(int colNumber) : This method returns the
values inside the column represented by colNumber.
AN EXAMPLE
public class InsertQueryExample
{
public static void main(String [] args)
{
try
{
String driverClass=“sun.jdbc.odbc.JdbcOdbcDriver”;
String url=“jdbc:odbc:dsn”;
String uname=“”;
String upass=“”;
Class.forName(driverClass);
Connection c=DriverManager.getConnection(url,uname,upass);
String query=“insert into db values(null,’atul’,’assist. Prof’);
Statement s=c.createStatement();
int res=s.executeUpdate(s);
if(res > 0)
System.out.println(“Values inserted successfully”);
}
catch(Exception e)
{
}
}
}
SECOND EXAMPLE
import java.sql.*;
public class SelectQueryExample
{
public static void main(String [] args)
{

try
{
Connection c= getConnection();
Statement stmt=c.createStatement();
String query=“select * from student”;
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
System.out.println(“Student Id=“+rs.getInt(1));
System.out.println(“Student Name=“+rs.getString(2));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
EFFECT OF NEXT() OPERATION
The next() method of ResultSet makes the cursor
forward. If the cursor is at the last row this method
returns false. Suppose the initial condition of
ResultSet is as follows

Col1

Col2

…

ColN

R00

R01

…

R0N

R10

R11

…

R1N

R20

R21

…

R2N
Now if we fire next() then the cursor moves forward
and the method returns true as the cursor pointing to
the first row.

Col1

Col2

…

ColN

R00

R01

…

R0N

R10

R11

…

R1N

R20

R21

…

R2N
Now if the cursor points to the last row then the next()
method returns false and cursor will not move forward.

Col1

Col2

…

C olN

R00

R01

…

R0N

R10

R11

…

R1N

R20

R21

…

R2N
IS THERE ANY METHOD PREVIOUS()?
The next() method of ResultSet moves the cursor one
row forward. The ResultSet interface defines the
following method to manipulate data retrieval from the
ResultSet.
1)

boolean previous() : Move the cursor one row
backward. If the cursor is pointing above the first
row, the method returns false.

2)

boolean first() : Move the cursor to the first row.

3)

boolean last() : Move the cursor to the last row.

4)

boolean relative(int n) : Moves the cursor to the
location n from the current position.
PROBLEMS WITH STATEMENT
Commonly we use java.sql.Statement interface to
execute sql queries. Here is a typical example of SQL
insert query
String
query=“insert
values(null,‟Atul‟,‟Vadodara‟)”;

into

student

Statement s=con.createStatement();

s.executeUpdate(query);
There are two major problems with this statement:
1) If we need to change the values then query will be
reconstructed and placed at different memory location.
Here is a typical memory layout for this scheme:
insert into student values(null,’Atul’,’Vadodara’)
0x3356FF9
The first query

insert into student values(null,’Prakash’,’Delhi’)
0x3356A80
The second query only value changed
2) We need to care about the quotes („). That means
values must be wrapped by quotes if the SQL syntax
requires that.

These two limitations makes Statement a less preferable
choice for programmers.
THE PREPAREDSTATEMENT
To avoid the complexity of Statement, Java provides another
interface called PreparedStatement
Here is a typical way to execute a insert query using
PreparedStatement.
String query=“insert into student values(null,?,?)”;

PreparedStatement p=con.prepareStatement(query);
p.setString(1,”Atul”);
p.setString(2,”Vadodara”);
p.executeUpdate();
Look at the query: instead of placing values a ? Is placed.
The ? is called positional parameter. The first ? is numbered
1, the second ? is numbered 2 and so on.
The values of each ? can be set using setXxx(int pos,
Xxx value);
Note: Xxx will be replaced by String, Int, Double, Float
ect. depending upon what datatype is used for the
position.
Second point : When we are setting the value of each ?
we are not taking care of quotes(„). The quotes will be
automatically wrapped by PreparedStatement.

When we supply any query to PreparedStatement then
instead of wasting memory, it just leave the blank space
for each ?. Now if we require to change the value only
blank space if filled with new values.
insert into student values(null,
________________,
________________
)

0x3356A79
Memory allocation for query by PreparedStatement

insert into student values(null, ‘Atul’,’Vadodara’)
0x3356A79
Query after setting the value
insert into student values(null, ‘Prakash’,’Delhi’)
0x3356A79

Query after changing the value.
Note that the memory location of the query remains
same and quotes are added.
SCROLLABLE RESULTSET
PreparedStatement gives us a very efficient way to create
precompiled (in terms of java only) queries. Memory
wastage and notorious quote problem are solved by it.
The PreparedStatement was introduced in Java 1.1. At
that time there is no way by which we can move backward
or jump at any location in ResultSet.
After the introduction of JDBC 2 the ResultSet is now
scrollable. That means the cursor can move both
backward and forward or jump to specific location in the
ResultSet. By default, the ResultSet in not scrollable.
That means
Connection c=…..;
String query=“select * from table”;
PreparedStatement p=c.prepareStatement(query);
ResultSet rs=p.executeQuery(); // oops rs is not scrollable
HOW TO MAKE RESULTSET SCROLLABLE
To make a ResultSet scrollable we need to use the
following method to get PreparedStatement object.
PreparedStatement prepareStatement(String query, int
type, int concurrency);

This method is defined in java.sql.Connection interface.
The type parameter may have following values:
Allowed values for type

purpose

ResultSet.TYPE_FORWARD_ONLY

The resultset is not
scrollable

ResultSet.TYPE_SCROLL_INSENSITIVE

The resultset is
scrollable but not
sensitive to
database change

ResultSet.TYPE_SCROLL_SENSITIVE

The resultset
scrollable and
sensitive to
database change
The concurrency parameter may have following values:
Allowed values for
concurrency

purpose

ResultSet.CONCUR_READ
_ONLY

The resultset can not be
used to update database

ResultSet.CONCUR_UPDA
TABLE

The resultset can be used
to update database.

Connection c=……;
String query=“select * from table”;

PreparedStatement
p=c.prepareStatement(query,ResultSet.TYPE_SCROLL_IN
SENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs=p.executeQuery(); // OK rs is scrollable but
not updatable
METHOD FOR SCROLLING RESULTSET
To traverse back and forth in ResultSet JDBC API
provides the following methods :
1) boolean previous() : Move the cursor one row
backward. If the cursor is pointing above the first row,
the method returns false.
2) boolean first() : Move the cursor to the first row.
3) boolean last() : Move the cursor to the last row.
4) boolean relative(int n) : Moves the cursor to the
location n from the current position.
5) void beforeFirst() : move the cursor before the first
row.
6) void afterLast() : move the cursor after the last row.
7) isBeforeFirst()
8) isAfterLast():
Test whether the cursor is before the first row or the last
row.
UPDATABLE RESULTSET
ResultSet is normally a memory snapshot of subset of
tables present inside the database and is a result of Select
query. Generally it is used only for data retrieval. But
sometimes while traversing the ResultSet we need to make
changes in our database.
By default a ResultSet is neither scrollable nor updatable.
That simply imply that we can not use a ResultSet to make
change in database. After the introduction of JDBC 2,
ResultSet can be made scrollable as well as updatable.
To make a ResultSet updatable we need to obtain ResultSet
as follows:
Connection c=……;
String query=“select * from table”;
PreparedStatement
p=c.prepareStatement(query,ResultSet.TYPE_SCROLL_INS
ENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=p.executeQuery(); // OK rs is scrollable and
updatable
MOVING FORWARD AND BACKWARD
Connection c=……;
String query=“select * from table”;
PreparedStatement
p=c.prepareStatement(query,ResultSet.TYPE_SCROLL
_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs=p.executeQuery();
rs.next(); // Move the cursor to first row
rs.next(); // Move the cursor to second row
rs.previous(); // Move the cursor to first row again

rs.last(); // place the cursor to last row
Col1

…

ColN

R00

R01

…

R0N

R10

R11

…

R1N

.

.

…

.

RM0


Col2

RM1

…

RMN

Effect of 2 next() operation
Col1

Col2

…

ColN

R00

R01

…

R0N

R10

R11

…

R1N

.

.

.

.

RM0

RM1

…

RMN


Effect of one previous() operation
Col1

Col2

…

ColN

R00

R01

…

R0N

R10

R11

…

R1N

.

.

.

.

RM0

RM1

…

RMN
UPDATING CURRENT ROW VALUES
Connection c=……;
String query=“select * from table”;
PreparedStatement
p=c.prepareStatement(query,ResultSet.TYPE_SCROLL
_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=p.executeQuery();
rs.next(); // Move the cursor to first row
rs.next(); // Move the cursor to second row
rs.updateString(2,”Prakash”); // Changing the value of
2nd column of 2nd row
rs.updateRow(); // Making effect permanent.


Initial Value
Col1

…

ColN

R00

R01

…

R0N

R10

R11

…

R1N

.

.

.

.

RM0


Col2

RM1

…

RMN

Effect of updateXxx and updateRow(see prev example)
Col1

Col2

…

ColN

R00

R01

…

R0N

R10

Prakash

…

R1N

.

.

.

.

RM0

RM1

…

RMN
INSERTING NEW VALUES
Connection c=……;
String query=“select * from table”;
PreparedStatement
p=c.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITI
VE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=p.executeQuery();
rs.next(); // Move the cursor to first row
rs.next(); // Move the cursor to second row
String id=0;
String name=“Dinesh”;
int age=25;
String gender-”Male”;
rs.moveToInsertRow(); // Move To the Row where insertion is
done
rs.updateInt(1,id); // update first column
rs.updateString(2,name); // update second column
rs.updateInt(3,age); // update third column
rs.updateString(4,gender); // update fourth column
rs.insertRow(); // make the effect permanent
rs.moveToCurrentRow(); // move to second row
Col1

Col2

…

ColN

R00

R01

…

R0N

R10

R11

…

R1N

.

.

.

.

RM0

RM1

…

R(M=1 R(M+1 …
))
)1

RMN

Insert Row

Cursor moved to insert row

Cursor moved back
Col1

Col2

…

ColN

R00

R01

…

R0N

R10

R11

…

R1N

.

.

.

.

RM0

RM1

…

RMN

R(M+1)0

R(M+1)1

…

R(M+1)N

Merged

R(M+1
)N
UPDATABLE METHODS SUMMARY
All the update related methods are defined in
java.sql.ResultSet interface.
1)

void moveToInsertRow() : moves the cursor to insert
row. The insert row is a special row for inserting new
data with updateXXX and insertRow methods.

2)

void moveToCurrentRow(): move the cursor back
from the insert row to the row that is occupied when
moveToInsertRow method was called.

3)

void insertRow(): insert the content of the insert row
into the database and resultset.

4)

void updateXxx(int colnumber,Xxx data) : update the
field in the current row of the resultset.

5)

void updateRow(): sends the current row updates to
the database.
METADATA
In SQL, data that describe the database or one of its
parts are called metadata. In general, metadata gives
the following information
1)
2)

3)
4)
5)

What is the structure of a database?
How many maximum connection that can be
established concurrently to the database?
How many rows are there in a table?
How many columns a table has?
Is ResultSet Scrollable or updatable ?

There are some other advanced information we can
collect from the metadata.
These information, in general, are not required for
application programmers. But these information are
highly required for those who want to design
advanced tools for database.
TYPES OF METADATA
On the basic of source of metadata, it is categorized
into three types
1)

Database Metadata
database itself.

:

The

information

about

2)

ResultSet Metadata : The information about the
ResultSet.

3)

PreparedStatement parameter: The information
about the parameters of prepared statement.

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Jdbc
JdbcJdbc
Jdbc
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 

Destaque

Destaque (10)

Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Java server pages
Java server pagesJava server pages
Java server pages
 
The java server pages
The java server pagesThe java server pages
The java server pages
 
The java enterprise edition (Servlet Basic)
The java enterprise edition (Servlet Basic)The java enterprise edition (Servlet Basic)
The java enterprise edition (Servlet Basic)
 
Losseless
LosselessLosseless
Losseless
 
Video Streaming - 4.ppt
Video Streaming - 4.pptVideo Streaming - 4.ppt
Video Streaming - 4.ppt
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Compression
CompressionCompression
Compression
 

Semelhante a Java database connectivity

Semelhante a Java database connectivity (20)

jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Lecture17
Lecture17Lecture17
Lecture17
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 
Jdbc
JdbcJdbc
Jdbc
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Jdbc
JdbcJdbc
Jdbc
 
22jdbc
22jdbc22jdbc
22jdbc
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 

Último

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 

Último (20)

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 

Java database connectivity

  • 1. JAVA DATABASE CONNECTIVITY A vendor neutral way to talk to database By Atul Saurabh Assist. Professor Babaria Institute of Technology
  • 2. THE DATABASE A database is an organized collection of data. -Wikipedia a) A file contains data in sequential form. Whenever we need to retrieve data from a file, we need to traverse the file character by character. b) There is no natural way to establish relation between file even though we can distribute data in different files. c) There is no effective way to check whether there is any redundancy in the file. d) There is no effective way to check the integrity of the data in a file.
  • 3. FORMS OF DATABASES On the basis of organization of data, database appears in different forms a) Relational Database : The data is organized in form of relations or tables. E.g. Oracle, MySQL, SyBase, Postgres etc. b) Hierarchal Database : The data is organized in some tree form. E.g. XML, LDAP ect. c) Object Oriented Database : The data is encapsulated in form of object. Each object represent a row from some table in other kind of database. E.g. Java Persistence API, Hibernate etc.
  • 4. TALKING TO THE DATABASE Each database vendor follows their own protocols for managing data inside database. Though the same syntax i.e. SQL is followed by every database vendor, their internal representation of data, i.e. datatype, is different. As for example MySQL uses float for floating type number but Oracle uses number(m,n) for the same. Programming language like Java provides its own syntax and datatypes. These diversities simply put a requirement of a layer which translate programming language representation into vendor specific representation. This layer is commonly known as database driver.
  • 5. PREREQUISITES FOR DATABASE CONNECTION Whenever a database is connected through some programming language following information is required: 1) The driver class 2) Authentication credentials for database engine 3) The URL to locate the database.
  • 6. STEPS TO CONNECT DATABASE THROUGH JAVA 1) Installation of vendor specific driver : Normally drivers comes in form of JAR file. Here are the names of some drivers a) ORACLE : oracle.jdbc.driver.OracleDriver b) MySQL : com.mysql.jdbc.Driver c) Postgres : org.postgresql.Driver d) ODBC : sun.jdbc.odbc.JdbcOdbcDriver There are three ways to install JDBC driver. i) Create a lib folder inside the project folder and place the JDBC driver JAR file inside lib and set classpath using manifest file.
  • 7. ii) CLASSPATH : set class path. Follow the steps : Create any directory inside the system say in D: drive create a directory with name library. Put the JAR file inside this folder. Let the name of jar is mysqlconnector-java-5.0.8-bin.jar. Now Go to My Computer |--Properties |---Advanced System Setting |------Environmental Variable |---- User Variable |-----New The following windows appears :
  • 8. In variable name write CLASSPATH In variable value write D:library mysql-connector-java-5.0.8-bin.jar; . (Mind the last . (dot) after semi-colon) iii) Place your JAR %JAVA_HOME%/jre/lib/ext directory. file If ODBC driver is used then no need to install the driver. Skip this step inside
  • 9. 2) Instantiate the driver : To instantiate the driver following code can be used class DatabaseConnection { public void makeConnection() { try { String driverClass=“sun.jdbc.odbc.JdbcOdbcDriver” Class.forName(driverClass); } catch(ClassNotFoundException e) { Logger.getLogger(DatabaseConnection.class.getName()).l og(Logger.SEVER,”The Driver Class Is Not Located”,e); } }
  • 10. 3) Establish the connection : Use DriverManager to establish the connection: public class DatabaseConnection { public void makeConnection() { try { String driverClass=“sun.jdbc.odbc.JdbcOdbcDriver” String username=“”; String passwd=“”; String url=“jdbc:odbc:dsn”; Class.forName(driverClass); Connection c=DriverManager.getConnection(url,username,passwd); if(!c.isClosed()) System.out.println(“Connection established”); } catch(ClassNotFoundException e) { Logger.getLogger(DatabaseConnection.class.getName()).log(Logger.SEVER, ”The Driver Class Is Not Located”,e); } catch(SQLException sqle){ Logger.getLogger(DatabaseConnection.class.getName()).log(Logger.SEVER, ”Unable To Connect”,sqle); } } }
  • 11. CREATING A DSN DSN stands for Data Source Name. It is required only if we are using ODBC driver. To create a DSN use the following steps : Go To Control Panel |----Administrative Tool |--- Data Source And create a System DSN by supplying the DSN name and selecting the database.
  • 13. TYPES OF JDBC DRIVERS Type 1: JDBC-ODBC Bridge Driver: In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the target database.
  • 14. Type 2: JDBC-Native API: In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database. These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.
  • 15. Type 3: JDBC-Net pure Java : In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network sockets to communicate with an middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.
  • 16. Type 4: 100% pure Java: In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself.
  • 17. SQL DATA TYPE AND CORRESPONDING JAVA TYPES Sl. No. SQL Data Type Java Data Type 1 INTEGER, INT int 2 SMALLINT short 3 NUMERIC(m,n), DECIMAL(m,n), DEC(m,n) java.math.BigDecimal 4 FLOAT(n) double 5 REAL float 6 CHARACTER(n), CHAR(n) String 7 VARCHAR(n) String
  • 18. Sl. No. SQL Data Type Java Data Type 8 BOOLEAN Boolean 9 DATE java.sql.Date 10 TIME java.sql.Time 11 TIMESTAMP java.sql.Timestamp 12 BLOB java.sql.Blob 13 CLOB java.sql.Clob 14 ARRAY java.sql.Array
  • 19. EXECUTING SQL QUERY In native SQL there are two types of queries a) The query which changes the values in one or more rows possibly by creating or deleting rows. E.g. INSERT, UPDATE, DELETE and ALTER. b) The query which simply returns the projection of one or more tables. E.g. SELECT. Whenever we execute query (a) then the query always returns us how many rows get affected. Whenever we execute query (b) we get a snapshot of subset original table(s). This snapshot is commonly known as ResultSet.
  • 20. The java.sql.Connection The Connection object represents a connection to the database. i) Statement createStatement() : This method is used to get the Statement object The java.sql.Statement The Statement object is used to execute a native SQL queries. i) ResultSet executeQuery(String query) : This method is used to execute query (b). ii) int executeUpdate(String query) : Used to execute query (a). iii) Int getUpdateCount() : Returns the number of records affected by previous update query.
  • 21. The java.sql.ResultSet The ResultSet is a snapshot of subset of original tables(s) . A ResultSet is always provided by a cursor. Initially cursor is pointed outside the table. We can visualize ResultSet as follows Col1 Col2 …. Coln R01 R02 …. R0n R11 R12 .... R1n R21 R22 …. R2n
  • 22. i) boolean next() : This method moves the cursor one row downward and returns true if there is any row available below the cursor. ii) Xxx getXxx(int colNumber) : This method returns the values inside the column represented by colNumber.
  • 23. AN EXAMPLE public class InsertQueryExample { public static void main(String [] args) { try { String driverClass=“sun.jdbc.odbc.JdbcOdbcDriver”; String url=“jdbc:odbc:dsn”; String uname=“”; String upass=“”; Class.forName(driverClass); Connection c=DriverManager.getConnection(url,uname,upass); String query=“insert into db values(null,’atul’,’assist. Prof’); Statement s=c.createStatement(); int res=s.executeUpdate(s); if(res > 0) System.out.println(“Values inserted successfully”); } catch(Exception e) { } } }
  • 24. SECOND EXAMPLE import java.sql.*; public class SelectQueryExample { public static void main(String [] args) { try { Connection c= getConnection(); Statement stmt=c.createStatement(); String query=“select * from student”; ResultSet rs=stmt.executeQuery(query); while(rs.next()) { System.out.println(“Student Id=“+rs.getInt(1)); System.out.println(“Student Name=“+rs.getString(2)); } } catch(Exception e) { e.printStackTrace(); } } }
  • 25. EFFECT OF NEXT() OPERATION The next() method of ResultSet makes the cursor forward. If the cursor is at the last row this method returns false. Suppose the initial condition of ResultSet is as follows Col1 Col2 … ColN R00 R01 … R0N R10 R11 … R1N R20 R21 … R2N
  • 26. Now if we fire next() then the cursor moves forward and the method returns true as the cursor pointing to the first row. Col1 Col2 … ColN R00 R01 … R0N R10 R11 … R1N R20 R21 … R2N
  • 27. Now if the cursor points to the last row then the next() method returns false and cursor will not move forward. Col1 Col2 … C olN R00 R01 … R0N R10 R11 … R1N R20 R21 … R2N
  • 28. IS THERE ANY METHOD PREVIOUS()? The next() method of ResultSet moves the cursor one row forward. The ResultSet interface defines the following method to manipulate data retrieval from the ResultSet. 1) boolean previous() : Move the cursor one row backward. If the cursor is pointing above the first row, the method returns false. 2) boolean first() : Move the cursor to the first row. 3) boolean last() : Move the cursor to the last row. 4) boolean relative(int n) : Moves the cursor to the location n from the current position.
  • 29. PROBLEMS WITH STATEMENT Commonly we use java.sql.Statement interface to execute sql queries. Here is a typical example of SQL insert query String query=“insert values(null,‟Atul‟,‟Vadodara‟)”; into student Statement s=con.createStatement(); s.executeUpdate(query); There are two major problems with this statement: 1) If we need to change the values then query will be reconstructed and placed at different memory location. Here is a typical memory layout for this scheme:
  • 30. insert into student values(null,’Atul’,’Vadodara’) 0x3356FF9 The first query insert into student values(null,’Prakash’,’Delhi’) 0x3356A80 The second query only value changed 2) We need to care about the quotes („). That means values must be wrapped by quotes if the SQL syntax requires that. These two limitations makes Statement a less preferable choice for programmers.
  • 31. THE PREPAREDSTATEMENT To avoid the complexity of Statement, Java provides another interface called PreparedStatement Here is a typical way to execute a insert query using PreparedStatement. String query=“insert into student values(null,?,?)”; PreparedStatement p=con.prepareStatement(query); p.setString(1,”Atul”); p.setString(2,”Vadodara”); p.executeUpdate(); Look at the query: instead of placing values a ? Is placed. The ? is called positional parameter. The first ? is numbered 1, the second ? is numbered 2 and so on.
  • 32. The values of each ? can be set using setXxx(int pos, Xxx value); Note: Xxx will be replaced by String, Int, Double, Float ect. depending upon what datatype is used for the position. Second point : When we are setting the value of each ? we are not taking care of quotes(„). The quotes will be automatically wrapped by PreparedStatement. When we supply any query to PreparedStatement then instead of wasting memory, it just leave the blank space for each ?. Now if we require to change the value only blank space if filled with new values.
  • 33. insert into student values(null, ________________, ________________ ) 0x3356A79 Memory allocation for query by PreparedStatement insert into student values(null, ‘Atul’,’Vadodara’) 0x3356A79 Query after setting the value
  • 34. insert into student values(null, ‘Prakash’,’Delhi’) 0x3356A79 Query after changing the value. Note that the memory location of the query remains same and quotes are added.
  • 35. SCROLLABLE RESULTSET PreparedStatement gives us a very efficient way to create precompiled (in terms of java only) queries. Memory wastage and notorious quote problem are solved by it. The PreparedStatement was introduced in Java 1.1. At that time there is no way by which we can move backward or jump at any location in ResultSet. After the introduction of JDBC 2 the ResultSet is now scrollable. That means the cursor can move both backward and forward or jump to specific location in the ResultSet. By default, the ResultSet in not scrollable. That means Connection c=…..; String query=“select * from table”; PreparedStatement p=c.prepareStatement(query); ResultSet rs=p.executeQuery(); // oops rs is not scrollable
  • 36. HOW TO MAKE RESULTSET SCROLLABLE To make a ResultSet scrollable we need to use the following method to get PreparedStatement object. PreparedStatement prepareStatement(String query, int type, int concurrency); This method is defined in java.sql.Connection interface. The type parameter may have following values: Allowed values for type purpose ResultSet.TYPE_FORWARD_ONLY The resultset is not scrollable ResultSet.TYPE_SCROLL_INSENSITIVE The resultset is scrollable but not sensitive to database change ResultSet.TYPE_SCROLL_SENSITIVE The resultset scrollable and sensitive to database change
  • 37. The concurrency parameter may have following values: Allowed values for concurrency purpose ResultSet.CONCUR_READ _ONLY The resultset can not be used to update database ResultSet.CONCUR_UPDA TABLE The resultset can be used to update database. Connection c=……; String query=“select * from table”; PreparedStatement p=c.prepareStatement(query,ResultSet.TYPE_SCROLL_IN SENSITIVE,ResultSet.CONCUR_READ_ONLY); ResultSet rs=p.executeQuery(); // OK rs is scrollable but not updatable
  • 38. METHOD FOR SCROLLING RESULTSET To traverse back and forth in ResultSet JDBC API provides the following methods : 1) boolean previous() : Move the cursor one row backward. If the cursor is pointing above the first row, the method returns false. 2) boolean first() : Move the cursor to the first row. 3) boolean last() : Move the cursor to the last row. 4) boolean relative(int n) : Moves the cursor to the location n from the current position. 5) void beforeFirst() : move the cursor before the first row. 6) void afterLast() : move the cursor after the last row. 7) isBeforeFirst() 8) isAfterLast(): Test whether the cursor is before the first row or the last row.
  • 39. UPDATABLE RESULTSET ResultSet is normally a memory snapshot of subset of tables present inside the database and is a result of Select query. Generally it is used only for data retrieval. But sometimes while traversing the ResultSet we need to make changes in our database. By default a ResultSet is neither scrollable nor updatable. That simply imply that we can not use a ResultSet to make change in database. After the introduction of JDBC 2, ResultSet can be made scrollable as well as updatable. To make a ResultSet updatable we need to obtain ResultSet as follows: Connection c=……; String query=“select * from table”; PreparedStatement p=c.prepareStatement(query,ResultSet.TYPE_SCROLL_INS ENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs=p.executeQuery(); // OK rs is scrollable and updatable
  • 40. MOVING FORWARD AND BACKWARD Connection c=……; String query=“select * from table”; PreparedStatement p=c.prepareStatement(query,ResultSet.TYPE_SCROLL _INSENSITIVE,ResultSet.CONCUR_READ_ONLY); ResultSet rs=p.executeQuery(); rs.next(); // Move the cursor to first row rs.next(); // Move the cursor to second row rs.previous(); // Move the cursor to first row again rs.last(); // place the cursor to last row
  • 41. Col1 … ColN R00 R01 … R0N R10 R11 … R1N . . … . RM0  Col2 RM1 … RMN Effect of 2 next() operation Col1 Col2 … ColN R00 R01 … R0N R10 R11 … R1N . . . . RM0 RM1 … RMN
  • 42.  Effect of one previous() operation Col1 Col2 … ColN R00 R01 … R0N R10 R11 … R1N . . . . RM0 RM1 … RMN
  • 43. UPDATING CURRENT ROW VALUES Connection c=……; String query=“select * from table”; PreparedStatement p=c.prepareStatement(query,ResultSet.TYPE_SCROLL _INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs=p.executeQuery(); rs.next(); // Move the cursor to first row rs.next(); // Move the cursor to second row rs.updateString(2,”Prakash”); // Changing the value of 2nd column of 2nd row rs.updateRow(); // Making effect permanent.
  • 44.  Initial Value Col1 … ColN R00 R01 … R0N R10 R11 … R1N . . . . RM0  Col2 RM1 … RMN Effect of updateXxx and updateRow(see prev example) Col1 Col2 … ColN R00 R01 … R0N R10 Prakash … R1N . . . . RM0 RM1 … RMN
  • 45. INSERTING NEW VALUES Connection c=……; String query=“select * from table”; PreparedStatement p=c.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITI VE,ResultSet.CONCUR_UPDATABLE); ResultSet rs=p.executeQuery(); rs.next(); // Move the cursor to first row rs.next(); // Move the cursor to second row String id=0; String name=“Dinesh”; int age=25; String gender-”Male”; rs.moveToInsertRow(); // Move To the Row where insertion is done rs.updateInt(1,id); // update first column rs.updateString(2,name); // update second column rs.updateInt(3,age); // update third column rs.updateString(4,gender); // update fourth column rs.insertRow(); // make the effect permanent rs.moveToCurrentRow(); // move to second row
  • 46. Col1 Col2 … ColN R00 R01 … R0N R10 R11 … R1N . . . . RM0 RM1 … R(M=1 R(M+1 … )) )1 RMN Insert Row Cursor moved to insert row Cursor moved back Col1 Col2 … ColN R00 R01 … R0N R10 R11 … R1N . . . . RM0 RM1 … RMN R(M+1)0 R(M+1)1 … R(M+1)N Merged R(M+1 )N
  • 47. UPDATABLE METHODS SUMMARY All the update related methods are defined in java.sql.ResultSet interface. 1) void moveToInsertRow() : moves the cursor to insert row. The insert row is a special row for inserting new data with updateXXX and insertRow methods. 2) void moveToCurrentRow(): move the cursor back from the insert row to the row that is occupied when moveToInsertRow method was called. 3) void insertRow(): insert the content of the insert row into the database and resultset. 4) void updateXxx(int colnumber,Xxx data) : update the field in the current row of the resultset. 5) void updateRow(): sends the current row updates to the database.
  • 48. METADATA In SQL, data that describe the database or one of its parts are called metadata. In general, metadata gives the following information 1) 2) 3) 4) 5) What is the structure of a database? How many maximum connection that can be established concurrently to the database? How many rows are there in a table? How many columns a table has? Is ResultSet Scrollable or updatable ? There are some other advanced information we can collect from the metadata. These information, in general, are not required for application programmers. But these information are highly required for those who want to design advanced tools for database.
  • 49. TYPES OF METADATA On the basic of source of metadata, it is categorized into three types 1) Database Metadata database itself. : The information about 2) ResultSet Metadata : The information about the ResultSet. 3) PreparedStatement parameter: The information about the parameters of prepared statement.