You are on page 1of 10

Chapter 05

Database
Introduction To JDBC ODBC
Java Database Connectivity(JDBC) is an Application Programming
Interface(API) used to connect Java application with Database.
JDBC is used to interact with various type of Database such as Oracle, MS Access,
My SQL and SQL Server. It allows java program to execute SQL statement and
retrieve result from database.
The JDBC API consists of classes and methods that are used to perform various
operations like: connect, read, write and store data in the database.
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.

Common JDBC Components


The JDBC API provides the following interfaces and classes −
DriverManager: This class manages a list of database drivers. Matches
connection requests from the java application with the proper database driver
using communication sub protocol. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database Connection.
Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication
with database is through connection object only.
Statement: You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.
ResultSet: These objects hold data retrieved from a database after you
execute an SQL query using Statement objects.
SQLException: This class handles any errors that occur in a database
application.

Java Database Connectivity (JDBC) is an application programming interface i.e.


(API). JDBC was released as a part of Java development Kit (JDK) 1.1. in the year
1996 by SUN Microsoft.
It is built the basis of ODBC and hence, some basics of ODBC retain in JDBC.
It is a standard interface between any Java application and different databases.
The function of JDBC is to help the Java-based application to access different types
of databases.
As JDBC is language and platform specific, Java application can use JDBC-to-ODBC
bridge to communicate with ODBC adaptable databases.
JDBC is low level interface .

ODBC is Open Database Connectivity.


Like JDBC, ODBC is also an API that acts as an interface between an application on
the client side and the database on the server side. Microsoft introduced ODBC in the
year 1992.ODBC helps an application to access the data from the database.
An application written in any language can use ODBC to access different types of
databases and hence, it is said to be language and platform independent.
Like JDBC, ODBC also provides ODBC drivers that convert the request of
application written in any language into the language understandable by databases.

Types of JDBC Architecture(2-tier and 3-tier)

The JDBC architecture consists of two-tier and three-tier processing models to access
a database.
Two-tier model
A java application communicates directly to the data source. The JDBC driver
enables the communication between the application and the data source. When a user
sends a query to the data source, the answers for those queries are sent back to the
user in the form of results.
The Java application/applet and the database can be on the same machine, or the
database can be on a server and the Java application/applet can be on a client machine
using any network protocol.
Three-tier model
In this, the user’s queries are sent to middle-tier services, from which the commands
are again sent to the data source. The results are sent back to the middle tier, and from
there to the user.
In a three-tier model, a Java application/applet communicates with a middle tier
component that functions as an application server. The application server talks to a
given database using JDBC.

JDBC Drivers Types


JDBC driver implementations vary because of the wide variety of operating systems
and hardware platforms in which Java operates.
Sun has divided the implementation types into four categories,
Types 1, 2, 3, and 4

Type 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. Oracle does not support the JDBC-ODBC Bridge from Java 8.
Type 2 driver – Native-API driver
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which
are unique to the database.
These drivers are typically provided by the database vendors and used in the same
manner as the JDBC-ODBC Bridge.
Native API must be installed in the Client System and hence type 2 drivers cannot be
used for the Internet.

Type 3: JDBC-Net pure Java


Network-Protocol driver (middleware 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.
Type 4 driver – Database-Protocol driver/Thin Driver(Pure
Java 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.
It converts JDBC calls into network protocol.
Type 3 and Type 4 drivers can be used either applet or servlet code.

Navigating a Result Set


Commonly used methods of ResultSet interface
Method Description
is used to move the cursor to the one row next
1) public boolean next():
from the current position.
is used to move the cursor to the one row
2) public boolean previous():
previous from the current position.
is used to move the cursor to the first row in
3) public boolean first():
result set object.
is used to move the cursor to the last row in result
4) public boolean last():
set object.
is used to move the cursor to the specified row
5)public boolean absolute(int row):
number in the ResultSet object.
is used to move the cursor to the relative row
6) public boolean relative(int row): number in the ResultSet object, it may be
positive or negative.

Java Database Connectivity Steps

There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
 Register the Driver class
 Create connection
 Create statement
 Execute queries
 Close 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 ClassNotFoundException

Example:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
2) Create the connection object

The getConnection() method of DriverManager class is used to establish


connection with the database.

Syntax of getConnection() method-


public static Connection getConnection(String url,String name,String password)
throws SQLException
Example:
Connection
con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/emp”,”root”,””);
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:
Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries(Select *
from tablename) to the database. This method returns the object of ResultSet that can
be used to get all the records of a table.
The executeUpdate() is used to execute DML commands(create, drop, insert, update,
delete).

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.getString(2));
}

5) Close the connection object

By closing 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
con.close();

Program for database connectivity using MySQL

import java.sql.*;
class Myconnectivity
{
public static void main(String args[])
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/emp","root","");
//here emp is database name, root is username and blank password
Statement stmt=con.createStatement();

String i="insert into emptable values(3,'abd',100,'Teacher')";


stmt.executeUpdate(i);

String d="delete from emptable where id=4";


stmt.executeUpdate(d);

String u="Update emptable set name='rohan' where id=1";


stmt.executeUpdate(u);

ResultSet rs=stmt.executeQuery("select * from emptable");


while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3)+"
"+rs.getString(4));

con.close();
}
catch(Exception e)
{ System.out.println(e);}
}
}
Output:

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.

Program using PreparedStatement

Design the form using JLabel, JTextField, JButton and JTable

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

Method Description
public void setInt(int paramIndex,
sets the integer value to the given parameter index.
int value)
public void setString(int
sets the String value to the given parameter index.
paramIndex, String value)
public void setFloat(int
sets the float value to the given parameter index.
paramIndex, float value)
public void setDouble(int
sets the double value to the given parameter index.
paramIndex, double value)
executes the query. It is used for create, drop,
public int executeUpdate()
insert, update, delete etc.
executes the select query. It returns an instance of
public ResultSet executeQuery()
ResultSet.
ResultSet MetaData
The metadata means data about data i.e. we can get further information from the data.

If you have to get metadata of a table like total number of column, column name,
column type etc. ,

ResultSetMetaData interface is useful because it provides methods to get metadata


from the ResultSet object.

ResultSetMetaData is used to get information about Resultset.

Method Description
public int getColumnCount() throws It returns the total number of columns in the
SQLException ResultSet object.
public String getColumnName(int it returns the column name of the specified
index) throws SQLException column index.
public String getColumnTypeName it returns the column type name for the
(int index) throws SQLException specified index.
public String getTableName(int index) it returns the table name for the specified
throws SQLException column index.

You might also like