0% found this document useful (0 votes)
19 views13 pages

Interacting With Databse

Uploaded by

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

Interacting With Databse

Uploaded by

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

5.

Interacting with Database


Java interacts with database using a common database application
programming interface called as JDBC.
The JDBC API is available in two packages-
1.Core API java.sql
2.standard extension to JDBC API javax.sql
JDBC defines a few steps to connect to a database and
retrieve/insert/update databases.
The steps are as follows-
1.Load the driver
2.Establish connection
3.create statements
4.Execute query and obtain result
5.iterate through the results.
1.Load the Drivers –
If your program needs a database connection, then first step is to
load the drivers. It is done automatically .But for manual loading of
database driver static method is used-
Class.forName(drivername)
Every database has its own driver .Driver names for few databases:
Database name Database drivers
MS Access sun.jdbc.odbc.JdbcOdbcDriver
Oracle oracle.jdbc.driver.OracleDriver
Microsoft sql com.microsoft.sqlserver.jdbc.SQLserverDriver
server 2000
MySQL org.gjt.mm.mysql.Driver
All the JDBC drivers have been classified into four categories:
1.JDBC ODBC Bridge Driver
2.Native API/Partly java driver
3.net protocol driver
4.pure java driver.

1.Type 1-jdbc odbc driver:


This translates all JDBC call to ODBC and send it to JDBC driver.
ODBC API is available in the administrative tools of the control
panel ,present in all microsoft operating systems.
Data sources name (DSN)is created by the programmer through
ODBC API . DSN keeps the record of which database needs to be
accessed, the location of database and the driver needed to access
the database Optional attributes like user-id and password are also
maintained with DSN.
There are three types of DSN-
1.User DSN-for a specific user
2.System DSN -for all users on the machine
3.File DSN -for all users who have same drivers installed and the users
can be on different machines.
Java 8 has removed JDBC ODBC bridge from driver class
sun.jdbc.odbc.jdbcodbcdriver from jdk and jre.
This class is required to connect database using Object database
connectivity driver eg. Micrososft access.
2.Type 2 Driver:Native API Driver
In type 2 driver ,JDBC calls the native API driver which calls the
database native API to connect to the database .
The oracle call interface (OCI) is an example of Type 2 driver.
These drivers enable JDBC programs to use database specific API s
that allow client programs to access databases via the java native
interfaces.

3.Type 3 Driver :Network protocol ,pure java driver


These drivers are written purely in java and used in networked
environment .
The request are routed to middle tier which converts JDBC calls to
database specific calls.

3.Type 4 Driver: Pure java driver/Thin driver


It is pure java driver that is used to connect to the database directly.

Java Interfaces and Driver Manager class


Java provides various interfaces for connecting to the database and
executing SQL statements.
Sr no Interfaces/classes Description
1 Connection The interface connects your java
application to the database
2 Driver An interface provides vendor specific
implementation of the abstract classes
provided by JDBC API
Each driver should supply a class that
implements the driver interface.
3 Statement An interface for executing normal SQL
statements
4 PreparedStatement An interface used to execute dynamic
SQL statements
5 ResultSet An interface that accepts result from
SQL select statement.
6 DriverManager Class that defines the object that
connect java application to a JDBC
driver.
It loads all the drivers found in system
properly and select the most
appropriate driver from opening a
connection to database.Acts as
interface between user and drivers.
It maintains the list of drivers classes
that have registered themselves by
calling the method
DriverManager.registerDriver().

2.Establish Connection –
A connection to the database is established using the static method
getConnection(databaseUrl) of the DriverManager class.It is the class
for managing JDBC drivers.
The database URL takes the following shape
jdbc:subprotocol:subname.
If any problem occurs during accessing the database ,an
SQLexception is generated,else a connection object is returned which
refers to a connection to a database.
Connection is actually an interface in java.sql package
Connection con =DriverManager.getConnection(databaseURL)

3.Create statement:
The connection after being established is used to send SQL
statements to the database .There are three interfaces in java.sql
package used for sending SQL statements to database ,namely –
Statement and its two subinterfaces-
PreparedStatement and callablestatement.
Three methods of the Connection object are used to return objects of
theses three statements.
A Statement object is used to send a simple SQL statement to the
database with no parameters .Its object are returned by using
createStatement() of the connection object.

Statement stmt = con.createStatement()

A preparedStatement object sends precompiled statements to the


databases with or without N parameters. Normally ,we insert rows of
data into the databases using insert SQL statement.For every
insertion ,we write an insert SQL statement which is sent to the
database .If n rows need to be inserted then the same statement gets
compiled n number of times.It consumes lot of time .so to increase
efficiency ,we use precompiled PreparedStatement.In this case ,only
the values that have to be inserted are sent to the database again and
again.

PreparedStatement ps =con.prepareStatement(String query)


A CallableStatement object is used to call stored procedures.It is
created using prepareCall() method.

CallableStatement cs =con.prepareCall(String query);

4.Execute Query:
The SQL statements are executed with the help of three methods
provided by the Statement interface.
ResultSet executeQuery(String sqlQuery ) throws SQLException
Int executeUpdate(String sqlQuery) throws SQLException
Boolean execute(String sqlQuery) throws SQLException

The executeQuery() is used for executing SQL statements that return


a single ResultSet,
For eg.a select statement ,the rows fetched from database are
returned as a single ResultSet object .
For example,
ResultSet rs =stmt.execuetQuery(“select * from emp”);

The method executeUpdate() is used for DDL and DML SQL


statements like insert ,update ,delete and create.This method will
return an integer value for DML to indicate the number of rows
affected /inserted (also known as updateCount) and 0 for DDL
statements which do not return anything.
For Example.
PreparedStatement ps=con.prepareStatement(“update emp set
salary = ? where empid =?”);
The statement is sent to database and is prepared for execution ,only
the value of the N(?) parameters need to be sent.

ps.setInt(1,10000);
ps.setString(2,”Emp001”);
ps.executeUpdate();

The PreparedStatement has certain methods that are used to set


value for N parameters as shown in the lines of code above .
In setInt(1,10000) ,the first argument is the position of the
parameters.This method will set salary=10000 and the method
setString(2,”Emp001”) sets the second IN parameter in the query i.e.
where empid=”Emp001”.
The execute method is used for callable statement when the
statement may return more than one ResultSet or update counts or a
combination of both .This happens when stored procedures are
executed.
5.Iterate ResultSet:
The resultSet is iterated with the help of a method next() which
returns a Boolean value to indicate that the ResultSet has more rows
to be iterated .
The next() that will move the cursor to the next row. The individual
column data is obtained by using accessor i.e getX() method .
For example, if the first column string, the method to fetch its value
is getString(1).
Similar methods are available for other data types:
For int, the method is int getInt(int columnIndex)
For long ,the method is long getLong(int columnIndex)
For float ,the method is long getFloat(int columnIndex)
For short, the method is long getShort(int columnIndex)
For Boolean ,the method is long getBoolean(int columnIndex)
For byte, the method is long getByte(int columnIndex)
For Date, the method is Date getDate(int columnIndex)

The code shown below is used for iterating the ResultSet:


While(rs.next())
{
System.out.println(rs.getString(1));
System.out.println(rs.getInt(2));
}
Column Indexing ResultSet starts from 1 not 0.

Now ,how do we know what is the type of data in the first /second
columns so that the appropriate methods can be used , and how
many columns are returned in the ResultSet?
All the these details can be obtained using a ResultSetMetaData
object. This object is used to obtain metadata about ResultSet that
include number of columns ,types of columns etc.
The method getMetaData() is used to return the ResultSetMetaData
Object.
The method getColumnCount() is used to return the number of
columns in the ResultSet.
The method getColumnTypeName(int columnIndex) returns the type
of data the column holds.

ResultSetMetaData rsmd =rs.getMetaData();


System.out.printl(“column in ResultSet:” +rsmd.getColumnCount());
For(int i=1;i<=rsmd.getColumnCount();i++)
{
System.out.println(“Column Name :” +rsmd.getColumnName(i));
System.out.println(“Column Type :” +rsmd.getColumnTypeName(i));
}

Note: A ResultSet object is automatically closed when the statement


object (from which Resultset was obtained) is closed or reexecuted.
Program to demonstrate how data is stored and retrieved from a
database.Assuming that an emp table is already created in MS-Access
with three attributes:EmpID ,Name, and salary.To access the database
of dsn by the name “sac” is also created.
Import java.sql.*;
Class DatabaseConnection
{
Public static void main(String args[])
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =DriverManager.getConnection(“jdbc:odbc:sac”);
PreparedStatement ps=con.prepareStatement(“insert into emp
values(?,?,?)”);
Ps.setString(1,”Emp001”);
Ps.setString(2,”Peter”);
Ps.setString(3,”10000”);
System.out.println(“Row inserted :” +ps.executeUpdate());
Statement stmt =con.createStatement();
ResultSet rs =stmt.executeQuery(“select * from emp”);
//obtaining metadata of resultset
ResultSetMetaData rsmd =rs.getMetaData();
Int cc=rsmd.getColumnCount();
System.out.println(“Number of columns in result set:” +cc);
for(int i=1;i<=cc;i++)
{
System.out.println(rsmd.getColumnName(i)+”\t”);
System.out.println();
While(rs.next())
{
System.out.println(rs.getString(1)+”\t”);
System.out.println(rs.getString(2)+”\t”);
System.out.println(rs.getString(3)+”\n”);
}
}
}

Output:Row inserted:1
Number of columns in result set: 3
EmpId Name salary
Emp001 Peter 10000

Scrollable ResultSet:
The ResultSet ,before JDBC 2.1 could be scrolled in the forward
direction only.Jdbc 2.1 introduced the concept of moving the cursor
in the backward direction also. We can even position the cursor of
ResultSet object on specific row .
But in order to use scrollable result set methods ,the scrollable
resultset must be obtained .this is specified at the statement creation
time by passing the following ResultSet Types in the
createStatement() method.
Following are the methods of ResultSet interface used for scrolling
through it.
first() Moves the cursor to the first row
of the ResultSet.
last() Moves the cursor to the last row
of the ResultSet
previous() Moves the cursor to the previous
row of the ResultSet
absolute(int row) Moves the cursor to the
specified row of the ResultSet
relative(int row) Moves the cursor to the relative
to the current row of the
ResultSet.A negative value can
be specified to move backward
and positive value to move
forward.
getRow() Returns current row number.

You might also like