Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

Interacting with Database

ODBC
• ODBC stands for Open Database
Connectivity
• It is a standard or open application
programming interface (API) for accessing a
database.
• ODBC provides an interface for database
access on Windows environment.
JDBC
• JDBC stands for Java Database Connectivity.
• It is a standard Java API for connecting
programs written in Java to the data in
relational databases.
• JDBC works with Java on a variety of
platforms, such as Windows, Mac OS, and
the various versions of UNIX.
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)
⮚JDBC-Net pure Java/ Network-Protocol driver (fully
java driver)
⮚Pure Java Driver /Thin driver / Database-Protocol
driver(fully java driver)
JDBC-ODBC bridge driver
• The JDBC type 1 driver, also known as the 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. Oracle recommends that you use JDBC
drivers provided by the vendor of your database
instead of the JDBC-ODBC Bridge.

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.
Native API driver
• The JDBC type 2 driver, also known as the 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.
JDBC-Net pure Java Driver
• The JDBC type 3 driver, also known as the Pure Java driver for
database middleware. It is a database driver implementation
which makes use of a middle tier between the calling program and
the database.
• The middle-tier (application server) converts JDBC calls directly or
indirectly into a 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.
Thin driver
• The JDBC type 4 driver, also known as the Direct to
Database Pure Java Driver, is a database driver implementation
that converts JDBC calls directly into a 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 depend on the Database.
JDBC two tier model
• In a two-tier model, a Java application communicates
directly with the database, via the JDBC driver.
• In the two-tier model, a Java applet or
application talks directly to the data source.
• This requires a JDBC driver that can
communicate with the particular data source
being accessed.
• A user's commands are delivered to the
database or other data source, and the results
of those statements are sent back to the user.
• The data source may be located on another
machine to which the user is connected via a
network.
JDBC three tier model
• In a three-tier model, a Java application
communicates with a middle tier component that
functions as an application server. The application
server talks to a given database using JDBC.
• In the three-tier model, commands are sent to
a "middle tier" of services, which then sends
the commands to the data source.
• The data source processes the commands and
sends the results back to the middle tier,
which then sends them to the user.
Application Server?
An application server is a program that resides on the server-side, and it’s a server programmer providing
business logic behind any application. This server can be a part of the network or the distributed network.

Working
They are basically used in a web-based application that has 3 tier architecture. The position at which the
application server fits in is described below:

● Tier 1 – This is a GUI interface that resides at the client end and is usually a thin client (e.g. browser)
● Tier 2 – This is called the middle tier, which consists of the Application Server.
● Tier 3 – This is the 3rd tier which is backend servers. E.g., a Database Server.
As we can see, they usually communicate with the webserver for serving any request that is coming from

clients. The client first makes a request, which goes to the webserver. The web server then sends it to the

middle tier, i.e. the application server, which further gets the information from 3 rd tier (e.g. database server)

and sends it back to the webserver. The web server further sends back the required information to the client.

Different approaches are being utilized to process requests through the web servers, and some of them are

approaches like JSP (Java server pages), CGI(Common Gateway Interface), ASP (Active Server Pages), Java

Scripts, Java servlets, etc.


Common JDBC Components
• The JDBC API provides the following interfaces
and classes −
• DriverManager Class
• Driver Interface
• Connection Interface
• Statement Interface
• ResultSet Interface
Common JDBC Components
DriverManager Class
• The DriverManager class acts as an interface
between user and drivers.
• It keeps 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
Method Description

is used to register the given


public static void registerDriver( Driver driver);
driver with DriverManager.

is used to deregister the given


public static void deregisterDriver( Driver
driver (drop the driver from the
driver);
list) with DriverManager.

is used to establish the


public static Connection getConnection (
connection with the specified
String url);
url.

public static Connection getConnection( is used to establish the


String url, String userName, String connection with the specified
password); url, username and password.
Driver Interface

• This interface handles the communications with


the database server.
• You will very rarely interact directly with Driver
objects.
• Instead, you use DriverManager objects, which
manages objects of this type.
Connection Interface

• A Connection is the session between java


application and database.
• The Connection interface provides many
methods for transaction management like
commit(), rollback() etc.
• When getConnection() method is called, it
returns a connection object.
Connection con=DriverManager.getConnection(URL);
Commonly used methods of Connection interface
Method Description

public Statement creates a statement object that can


createStatement(); be used to execute SQL queries.

public void It is used to set the commit status.


setAutoCommit(boolean status); By default it is true.

It saves the changes made since


public void commit(); the previous commit/rollback
permanent.
Drops all changes made since the
public void rollback(); previous commit/rollback.
closes the connection and Releases
public void close(); a JDBC resources immediately.
Statement Interface

• The Statement interface provides methods to


execute queries with the database.
• It provides factory method to get the object of
ResultSet.
• PreparedStatement interface
• The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.
• String sql="insert into emp values(?,?,?)";
Commonly used methods of Statement interface
Method Description

public ResultSet used to execute SELECT query. It


executeQuery(String sql); returns the object of ResultSet.

used to execute specified query, it


public int executeUpdate(String
may be create, drop, insert, update,
sql);
delete etc.
Returns a boolean value of true if a
ResultSet object can be retrieved;
public boolean execute(String
otherwise, it returns false. Use this
sql);
method to execute SQL DDL
statements
public int[] executeBatch(); used to execute batch of commands.

void close() Close the statement object


ResultSet Interface

• A ResultSet object provides access to a table of


data.
• ResultSet object is usually generated by
executing a statement.
• The object of ResultSet maintains a cursor
pointing to a particular row of data.
• Initially, cursor points before the first row.
Commonly used methods of ResultSet interface
Method Description
public boolean next(); is used to move the cursor to the one row next from the
current position.
public boolean previous(); is used to move the cursor to the one row previous from the
current position.This method returns false if the previous row
is off the result set.
public boolean first(); is used to move the cursor to the first row in result set object.
public boolean last(); is used to move the cursor to the last row in result set object.
public boolean absolute(int is used to move the cursor to the specified row number in the
row); ResultSet object.
public int getInt(int is used to return the data of specified column index of the
columnIndex); current row as int.
public int getInt(String is used to return the data of specified column name of the
columnName); current row as int.
public String getString(int is used to return the data of specified column index of the
columnIndex); current row as String.
public String is used to return the data of specified column name of the
getString(String current row as String.
columnName);
Connecting to Database
• There are 5 steps to connect any java
application with the database in java using
JDBC. They are as follows:
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
1.Register the driver class
• The Class.forName() method is used to register the driver
class. This method is used to dynamically load the driver
class. The Class.forName is used to load any given class (within
double quotes as String) at run time.

• Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException

• Example to register with JDBC-ODBC Driver


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
1.Register the driver class
• Approach I - Class.forName()
• The Class.forName() method is used to register the driver class. This method is
used to dynamically load the driver class. The Class.forName is used to load any
given class (within double quotes as String) at run time.
• Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
• Example to register with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");

Approach II - DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method. Ex.
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
2. Creating connection
• The DriverManager.getConnection() method is used
to establish connection with the database.

• Example establish connection with Oracle Driver


Connection con = DriverManager.getConnection
("jdbc:odbc:DemoDB","username","password");
3. Creating statement

• The createStatement() method of Connection interface


is used to create statement. The object of statement is
responsible to execute queries with the database.

• Example to create the statement object


Statement stmt=con.createStatement();
4. Executing queries
• 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.

• Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5. Closing connection
• By closing connection object statement and
ResultSet will be closed automatically.
• The close() method of Connection interface is used
to close the connection.

• Example to close connection

con.close();
Example to Connect Java Application
with mysql database
import java.sql.*;
class MysqlCon{
public static void main(String args[])
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Emp","roo
t","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e) {
System.out.println(e); }
}
Connection with Oracle Database
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:
1. 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.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
How to get the instance of PreparedStatement?
The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:
1. public PreparedStatement prepareStatement(String query)throws
SQLException{}
Methods of PreparedStatement interface
The important methods of PreparedStatement interface are given below:
Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter
value) index.
public void setString(int paramIndex, sets the String value to the given parameter
String value) 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 parameter
paramIndex, double value) index.

public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance


of ResultSet.
Example of PreparedStatement interface that inserts the record
First of all create table as given below:
1. create table emp(id number(10),name varchar2(50));
Now insert records in this table by the code given below:
1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:
xe","system","oracle");
7. PreparedStatement stmt=con.prepareStatement("insert into Emp
values(?,?)");
8. stmt.setInt(1,101);//1 specifies the first parameter in the query
9. stmt.setString(2,"Rtan");
10. int i=stmt.executeUpdate();
11.System.out.println(i+" records inserted");
12. con.close(); }catch(Exception e){ System.out.println(e);} } }
Example of PreparedStatement interface that updates the record
1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where
id=?");
2. stmt.setString(1,"Ratna");//1 specifies the first parameter in the query i.e. name
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");

Example of PreparedStatement interface that deletes the record


1. PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
2. stmt.setInt(1,101);
3.
4. int i=stmt.executeUpdate();
Example of PreparedStatement interface that retrieve the records of a
table
1. PreparedStatement stmt=con.prepareStatement("select * from
emp");
2. ResultSet rs=stmt.executeQuery();
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }
Example of PreparedStatement to insert
1. System.out.println("enter salary:");
records until user press n
2. float
1. import java.sql.*;
salary=Float.parseFloat(br.readLine());
2. import java.io.*;
3.
3. class RS{
4. ps.setInt(1,id);
4. public static void main(String
5. ps.setString(2,name);
args[])throws Exception{
6. ps.setFloat(3,salary);
5. Class.forName("oracle.jdbc.driver.Oracle
7. int i=ps.executeUpdate();
Driver");
8. System.out.println(i+" records
6. Connection
affected");
con=DriverManager.getConnection("jdbc:
9.
oracle:thin:@localhost:1521:xe","system",
10. System.out.println("Do you want to
"oracle");
continue: y/n");
7. PreparedStatement
11. String s=br.readLine();
ps=con.prepareStatement("insert into
12. if(s.startsWith("n")){
emp130 values(?,?,?)");
13. break;
8. BufferedReader br=new
14. }
BufferedReader(new
15. }while(true);
InputStreamReader(System.in));
16.
9. do{
17. con.close();
10. System.out.println("enter id:");
18. }}
11. int id=Integer.parseInt(br.readLine());
12. System.out.println("enter name:");
13. String name=br.readLine();
Connection with Access Database
import java.sql.*;
public class JdbcAccessTest {
public static void main(String[] args) {
String databaseURL = "jdbc:ucanaccess://e://Contacts.accdb";
try (
Connection connection = DriverManager.getConnection(databaseURL)) {
String sql = "INSERT INTO Contacts (Full_Name, Email, Phone) VALUES (?, ?, ?)";
PreparedStatement preparedStatement =
connection.prepareStatement(sql);
preparedStatement.setString(1, "Rohit");
preparedStatement.setString(2, "rohit@mi.com");
preparedStatement.setString(3, "0919989998");
int row = preparedStatement.executeUpdate();

if (row > 0) {
System.out.println("A row has been inserted successfully.");
}
sql = "SELECT * FROM Contacts";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
int id = result.getInt("Contact_ID");
String fullname = result.getString("Full_Name");
String email = result.getString("Email");
String phone = result.getString("Phone");
System.out.println(id + ", " + fullname + ", " + email + ", " + phone);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}

You might also like