0% found this document useful (0 votes)
5 views6 pages

JDBC Notes

The document provides an overview of JDBC (Java Database Connectivity), explaining its importance for connecting Java applications to databases. It compares JDBC with ODBC, highlights JDBC architecture, and details the types of JDBC drivers and their functionalities. Additionally, it outlines the steps for establishing database connections, using PreparedStatement for parameterized queries, and describes different types of ResultSet for navigating through query results.

Uploaded by

adityapandji1
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)
5 views6 pages

JDBC Notes

The document provides an overview of JDBC (Java Database Connectivity), explaining its importance for connecting Java applications to databases. It compares JDBC with ODBC, highlights JDBC architecture, and details the types of JDBC drivers and their functionalities. Additionally, it outlines the steps for establishing database connections, using PreparedStatement for parameterized queries, and describes different types of ResultSet for navigating through query results.

Uploaded by

adityapandji1
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/ 6

IF4K/JPR/SMJ

UNIT VI : JDBC
An application should be connected to a database for storing the info provided by the user. This
is referred as database connectivity. The JDBC API is used to connect the application & the database & is
also responsible for the transfer of data between the two. In some cases multiple databases are used to
store the data. In such cases it becomes difficult to write code for establishing application database
connectivity with each of the database. This problem is solved by Ms Standard for comm. With database
called as ODBC API (open database connectivity)
Java programs cannot directly communicate with ODBC drivers. ODBC is written in C language. It
uses pointers & other constructs which are not supported in java.
 JDBC v/s ODBC
1. ODBC is not appropriate for direct use from java as it uses C interface.
2. Java does not support pointers & ODBC makes use of it.
3. ODBC driver managers must be manually installed on every client when it is needed where as
JDBC code is automatically installable, portable & secure.
4. ODBC is hard to learn & has complex options even for simple query.
5. ODBC is platform specify whereas JDBC is platform independent.

 JDBC Architecture
It consists of two layers as JDBC API & JDBC Driver API. JDBC API provides application to JDBC
Manager Connection & JDBC Driver API supports JDBC Manager to db driver connection.

Two models for data access are supported by JDBC API, they are – 2 tier model & 3 tier model.

JDBC 2- Tier Architecture


In 2-tier architecture java application communicates directly with database. The database may
reside on same machine or other machine in the network. The client will send the statement to
database and result will communicated back to the client.

In two tier model java application directly talks to the db. This requires JDBC driver that can
communicate with particular DBMS sys being accessed. SQL statements are delivered to
database & results are sent back to the application. It is referred to as client server application.
Page 1 of 6
IF4K/JPR/SMJ

JDBC 3- Tier Architecture


In 3-tier architecture a ‘middle-tier’ is used between java application and database. A java
application sends a command to middle-tier, which then further sends to database. The
database processes the query and returns the result to the middle-tier, which further returns to
the application. This approach has the many advantages such as better maintainability, easier
deployment, scalability, etc.

In 3 tier model commands are send to a middle tier of services, which sends SQL statements &
send the result back to middle tier & then to the user. The middle tier architecture can provide
performance advantages.

 JDBC Driver
There are 4 types of JDBC drivers:
1. JDBC ODBC bridge driver
This type of JDBC driver provides db access using ODBC driver. As a part of JDBC, sun
microsys provides a driver called as JDBC-ODBC-Bridge to access ODBC data source. The
bridge between JDBC & ODBC drivers translates JDBC operations into ODBC operations.

2. Native API partly Java driver


This kind of driver converts JDBC calls into calls on the client API. The advantage of using
this driver is that it reduces the complexity of client application. The client libraries are
usually written in C & C++. JDBC implementation uses a layer of C & C++ in order to call
these libraries.

3. JDBC net pure Java driver


This driver translates JDBC calls into DBMS independent net protocol which is then
translated to DBMS protocol by server.

4. Native protocol pure Java driver


This allows a direct call from client machine to DBMS server & is a practical solution for
intranet access.

Page 2 of 6
IF4K/JPR/SMJ

 Driver interface & Driver Manager class

Class/ Interface Function Methods


Driver Manager To get connection with getConnection(protocol,dsn)userna
Class data source name (DSN) me & password optional
where protocol for a bridge is
jdbc:odbc
Connection To make connection to createStatement()
Interface specific db using a specific
driver prepareStatement(query)
Can be used to create
statements for query
Statement To execute SQL Statements executeQuery(query)
Interface executeUpdate(query)
PreparedStatement It is the subclass of setInt(pos,value)
Interface statement & can be used to setText(pos,value)
execute precompiled SQL executeUpdate()
statement executeQuery()

ResultSet Interface Stores result of SQL query next()


Provides method to getMetaData()
retrieve data getColumnCount()
getColumnLabel()
getString(pos)
close()

DatabaseMetaData Can be used to provide


Interface information about
database such as version,
table name, supported
functions etc.
ResultSetMetaData Can be used to get getMetaData()
Interface information about column
type, number of columns,
properties of columns in
Resultset

For establishing connection with DSN and retrieving the data procedure is as follows:
(Note : this procedure works for jdk1.7 or prior, Type 1 driver is removed from JDK 1.8
onwards)
Driver can be registered with the syntax as follows :

Class.forName(“Driver name”);
Eg : Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Page 3 of 6
IF4K/JPR/SMJ

Steps :
(Note : Create DSN (Data Source Name) in case of the procedure with DSN connectivity)
1. Import java.sql.*; in the applicatication.
2. Register Database Driver.
3. Connect to database with getConnection().
4. Create a Statement.
5. Execute a Statement .
6. Store the result in a Resultset in case of ‘select’ query.
7. Retrieve result from ResultSet.
8. Close the Statement and Connection.

For establishing connection without DSN and retrieving the data the procedure is as follows:
In this case we have to find proper driver for the environment we are using at the backend.
For eg, if its MySql then the driver can be registered as :
Class.forName("com.mysql.jdbc.Driver");
Here the driver used is for Mysql database environment.
It can be as
Class.forName("com.mysql.cj.jdbc.Driver"); in some version where cj is Connector/J

Connection can be set as


con=DriverManager.getConnection("jdbc:mysql://localhost:3306/database
name","username","password");
 3306 is the default port reserved for mysql.
 Username and password are the authentication credentials from MySql.
 Database name is the name where tables are stored.
 Rest of the steps from 2 to 8 are same as mentioned above in with DSN procedure.

While compiling the program we require a jar file for getting access to mysql jdbc connector,
which can be downloaded and copied to c:\...\jdk folder\jre\lib\ext and set in the classpath
in environment variable or as set CLASSPATH = <classpath>
Or temporarily it can be used while compiling as :
javac -classpath c:\...\jdk..\jre\lib\ext\ mysql-connector-java-8.0.21 <java sourcecode>
jar filename may differ from version to version.

Programs for Practice:


1) WAP to display details of employee getting salary more than 5000.
2) WAP to accept salary of employee and display details of employee who get that salary.
3) WAP to increment salary by 20% of those employee who get salary more than 10,000.
4) WAP to insert a record into emp table as (101, ‘abc’,15000).
5) WAP to delete records of employee from deptno 20 & 30.

Page 4 of 6
IF4K/JPR/SMJ

 PreparedStatement Object

If an application executes a query according to search criteria specified by the user, it can be
done by a query statement that receives appropriate value in ‘where’ clause at runtime. For this
purpose PreparedStatement object can be created which can take input at runtime and can be
used to search criteria to display required results.

Unlike Statement object PreparedStatement object contains SQLStatement that is precompiled


and takes less time to process at the database end. The PreparedStatement object allows to
execute parameterized queries. These queries require parameter to be specified by the user.
PreparedStatement bject can be created by calling ‘prepareStatement()’ method of Connection
object. It takes SQLStatements as parameters. SQLStatement can contain placeholders that are
replaced by input paramaters at runtime.

Eg : PreparedStatement ps;
Ps= con.prepareStatement(“select * from emp where deptno =? Or deptno=?”);
Where ? represents placeholder.

Before executing PrepareStatement object, you must get the values for each ‘?’ parameter. It
can be done by the method ‘setXXX(position, value)’ where XXX- datatype.

Eg : setInt(1,20);
setInt(2,30);

setString(5,”abc”);
setFloat(3,35.5);

Programs for Practice :


6) WAP to accept a deptno from user and delete all the employees belonging to that
deptno.
7) Design an application which inserts record in emp table. The interface has following
layout :
Employee No :

Name :

Salary :

Insert data

Page 5 of 6
IF4K/JPR/SMJ

8) WAP to create student table with rollno, name and average through a java application.
9) WAP to display all records from student table.

Three types of ResultSet are


 Forward-only
This type of ResultSet can make the traversal for rows only in the forward direction and non-
scrollable.
 Scroll-insensitive
Scroll-insensitive ResultSet are not capable for scrolling. That means the cursor can move in only
one direction. When the ResultSet is open, any change to the database table will not reflect.
 Scroll-sensitive
Unlike Scroll-insensitive, the Scroll-sensitive ResultSet is capable to move the cursor in
bidirectional. It also enables the changes done to the database tables when open.

Methods to navigate through records from ResultSet:


Method name Use
public boolean isBeforeFirst() Retrieves whether the cursor is before the first row in
throws SQLException this ResultSet object.
public boolean isAfterLast() Retrieves whether the cursor is after the last row in
throws SQLException this ResultSet object.
public boolean isFirst() Retrieves whether the cursor is on the first row of
throws SQLException this ResultSet object.
public boolean isLast() Retrieves whether the cursor is on the last row of this
throws SQLException ResultSet object. Note: Calling the method isLast may be
expensive because the JDBC driver might need to fetch
ahead one row in order to determine whether the current
row is the last row in the result set.
public void beforeFirst() Moves the cursor to the front of this ResultSet object, just
throws SQLException before the first row. This method has no effect if the result
set contains no rows.
public void afterLast() Moves the cursor to the end of this ResultSet object, just
throws SQLException after the last row. This method has no effect if the resultset
contains no rows.
public boolean first() Moves the cursor to the first row in this ResultSet object.
throws SQLException
public boolean last() Moves the cursor to the last row in this ResultSet object.
throws SQLException
public boolean previous() Moves the cursor to the previous row in
throws SQLException this ResultSet object.
public boolean next() Moves the cursor down one row from its current position.
throws SQLException A ResultSet cursor is initially positioned before the first
row; the first call to the method next makes the first row
the current row; the second call makes the second row the
current row, and so on.

Page 6 of 6

You might also like