Sunteți pe pagina 1din 16

Introduction to JDBC

The JDBC (Java Database Connectivity) API defines interfaces and classes for
writing database applications in Java by making database connections. Using JDBC
you can send SQL, PL/SQL statements to almost any relational database. JDBC is a
Java API for executing SQL statements and supports basic SQL functionality. It
provides RDBMS access by allowing you to embed SQL inside Java code. Because
Java can run on a thin client, applets embedded in Web pages can contain
downloadable JDBC code to enable remote database access. You will learn how to
create a table, insert values into it, query the table, retrieve results, and update the
table with the help of a JDBC Program example.
Although JDBC was designed specifically to provide a Java interface to relational
databases, you may find that you need to write Java code to access non-relational
databases as well.

JDBC Architecture

Java application calls the JDBC library. JDBC loads a driver which talks to the
database. We can change database engines without changing database code.

JDBC Basics Java Database Connectivity Steps


Before you can create a java jdbc connection to the database, you must first import
the
java.sql package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package
java.sql are to be imported.
1. Loading a database driver,
In this step of the jdbc connection process, we load the driver class by calling
Class.forName() with the Driver class name as an argument. Once loaded, the
Driver class creates an instance of itself. A client can connect to Database Server
through JDBC Driver. Since most of the Database servers support ODBC driver
therefore JDBC-ODBC Bridge driver is commonly used.
1

The return type of the Class.forName (String ClassName) method is Class. Class
is a class in java.lang package.
1
2
3
4
5
6

try {
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Or any other driver
}
catch(Exception x){
System.out.println( Unable to load the driver class! );
}

2. Creating a oracle jdbc Connection


The JDBC DriverManager class defines objects which can connect Java applications
to a JDBC driver. DriverManager is considered the backbone of JDBC architecture.
DriverManager class manages the JDBC drivers that are installed on the system. Its
getConnection() method is used to establish a connection to a database. It uses a
username, password, and a jdbc url to establish a connection to the database and
returns a connection object. A jdbc Connection represents a session/connection with
a specific database. Within the context of a Connection, SQL, PL/SQL statements
are executed and results are returned. An application can have one or more
connections with a single database, or it can have many connections with different
databases. A Connection object provides metadata i.e. information about the
database, tables, and fields. It also contains methods to deal with transactions.
JDBC URL Example:: jdbc: <subprotocol>: <subname>Each driver has its own
subprotocol
Each subprotocol has its own syntax for the source. Were using the jdbc odbc
subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.
1
2
3
4
5
6

try{
Connection dbConnection=DriverManager.getConnection(url,loginName,Password)
}
catch( SQLException x ){
System.out.println( Couldnt get connection! );
}

Creating a jdbc Statement object


Once a connection is obtained we can interact with the database. Connection
interface defines methods for interacting with the database via the established
connection. To execute SQL statements, you need to instantiate a Statement object
from your connection object by using the createStatement() method.
Statement statement = dbConnection.createStatement();
A statement object is used to send and execute SQL statements to a database.
Three kinds of Statements
2

Statement: Execute simple sql queries without parameters.


Statement createStatement()
Creates an SQL Statement object.
Prepared Statement: Execute precompiled sql queries with or without parameters.
PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are
precompiled
SQL statements.
Callable Statement: Execute a call to a database stored procedure.
CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL
stored procedure call statements.

Executing a SQL statement with the Statement object, and returning a


jdbc resultSet.
Statement interface defines methods that are used to interact with database via the
execution of SQL statements. The Statement class has three methods for executing
statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the
method to use is executeQuery . For statements that create or modify tables, the
method to use is executeUpdate. Note: Statements that create a table, alter a table,
or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an
SQL
statement that is written as String object.
ResultSet provides access to a table of data generated by executing a Statement.
The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to
its current row of data. The next() method is used to successively step through the
rows of the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the
columns in a ResultSet. It is constructed from the Connection object.

Test JDBC Driver Installation


1
2
3
4
5

import javax.swing.JOptionPane;
public class TestJDBCDriverInstallation_Oracle {
public static void main(String[] args) {

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

StringBuffer output = new StringBuffer();


output.append(Testing oracle driver installation \n);
try {
String className = sun.jdbc.odbc.JdbcOdbcDriver;
Class driverObject = Class.forName(className);
output.append(Driver : +driverObject+\n);
output.append(Driver Installation Successful);
JOptionPane.showMessageDialog(null, output);
} catch (Exception e) {
output = new StringBuffer();
output.append(Driver Installation FAILED\n);
JOptionPane.showMessageDialog(null, output);
System.out.println(Failed: Driver Error: + e.getMessage());
}
}

Java JDBC Connection Example, JDBC Driver Example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

import
import
import
import

java.sql.Connection;
java.sql.DatabaseMetaData;
java.sql.DriverManager;
java.sql.SQLException;

public class JDBCDriverInformation {


static String userid=scott, password = tiger;
static String url = jdbc:odbc:bob;
static Connection con = null;
public static void main(String[] args) throws Exception {
Connection con = getOracleJDBCConnection();
if(con!= null){
System.out.println(Got Connection.);
DatabaseMetaData meta = con.getMetaData();
System.out.println(Driver Name : +meta.getDriverName());
System.out.println(Driver Version : +meta.getDriverVersion());
}else{
System.out.println(Could not Get Connection);
}

public static Connection getOracleJDBCConnection(){


try {
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
} catch(java.lang.ClassNotFoundException e) {
System.err.print(ClassNotFoundException: );
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, userid, password);
} catch(SQLException ex) {
System.err.println(SQLException: + ex.getMessage());
}

return con;

34
}

JDBC Driver Types

JDBC drivers are divided into four types or levels. The different types of jdbc
drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)
4 types of jdbc drivers are elaborated in detail as shown below:
Type 1 JDBC Driver
JDBC-ODBC Bridge driver

The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the
ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is
recommended only for experimental use or when no other alternative is available.

Type 1: JDBC-ODBC Bridge


Advantage
5

The JDBC-ODBC Bridge allows access to almost any database, since the
databases ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC
driver, then to the database, and this applies even in the reverse process. They are
the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
Type 2 JDBC Driver

Native-API/partly Java driver


The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert
JDBC calls into database-specific calls i.e. this driver is specific to a particular
database. Some distinctive characteristic of type 2 jdbc drivers are shown below.
Example: Oracle will have oracle native api.

Type 2: Native api/ Partly Java Driver


Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer
better performance than the JDBC-ODBC Bridge as the layers of communication

(tiers) are less than that of Type


1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot
be used for the Internet.
2. Like Type 1 drivers, its not written in Java Language which forms a portability
issue.
3. If we change the Database we have to change the native api as it is specific to a
database
4. Mostly obsolete now
5. Usually not thread safe.
Type 3 JDBC Driver

All Java/Net-protocol driver


Type 3 database requests are passed through the network to the middle-tier server.
The middle-tier then translates the request to the database. If the middle-tier server
can in turn use Type1, Type 2 or Type 4 drivers.

Type 3: All Java/ Net-Protocol Driver


Advantage
1. This driver is server-based, so there is no need for any vendor database library to
be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
7

3. There are many opportunities to optimize portability, performance, and scalability.


4. The net protocol can be designed to make the client JDBC driver very small and
fast to load.
5. The type 3 driver typically provides support for features such as caching
(connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Traversing the recordset
may take longer, since the data comes through the backend server.
Type 4 JDBC Driver

Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the database
server.

Type 4: Native-protocol/all-Java driver


Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely
written in Java to achieve platform independence and eliminate deployment
administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers dont have to
translate database requests to ODBC or a native connectivity interface or to pass
the request on to another server, performance is typically quite good.
8

3. You dont need to install special software on the client or server. Further, these
drivers can be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.

5 Steps to connect to the database in java


1.5 Steps to connect to the database in java
1.

Register the driver class

2.

Create the connection object

3.

Create the Statement object

4.

Execute the query

5.

Close the connection object

There are 5 steps to connect any java application with the database in java using JDBC.
They are as follows:
Register the driver class

Creating connection

Creating statement

Executing queries

Closing 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


1.

public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class


9

1.

Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with
the database.

Syntax of getConnection() method


1.
2.
3.

1) public static Connection getConnection(String url)throws SQLException


2) public static Connection getConnection(String url,String name,String password)
throws SQLException

Example to establish connection with the Oracle


database
1.
2.

Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");

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


1.

public Statement createStatement()throws SQLException

Example to create the statement object


1.

Statement stmt=con.createStatement();

4) Execute the query


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.

Syntax of executeQuery() method


10

1.

public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


1.
2.
3.
4.
5.

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


1.

public void close()throws SQLException

Example to close connection


1.

con.close();

Example to connect to the Oracle database


For connecting java application with the oracle database, you need to follow 5 steps to
perform database connectivity. In this example we are using Oracle10g as the database.
So we need to know following informations for the oracle database:
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is
running, we may also use IP address, 1521 is the port number and XE is the
Oracle service name. You may get all these informations from the tnsnames.ora
file.
3. Username: The default username for the oracle database is system.
4. Password: Password is given by the user at the time of installing the oracle
database.

1.

Let's first create a table in oracle database.


create table emp(id number(10),name varchar2(40),age number(3));

11

Example to Connect Java Application with Oracle


database
In this example, system is the username and oracle is the password of the Oracle database.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.

import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

download this example


The above example will fetch all the records of emp table.

To connect java application with the Oracle database ojdbc14.jar file is required to be
loaded.

download the jar file ojdbc14.jar

Two ways to load the jar file:


1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath

12

1) paste the ojdbc14.jar file in JRE/lib/ext folder:


Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file
here.

2) set classpath:
There are two ways to set the classpath:
temporary

permanent

How to set the temporary classpath:


1.

Firstly, search the ojdbc14.jar file then open command prompt and write:
C:>set classpath=c:\folder\ojdbc14.jar;.;

How to set the permanent classpath:


Go to environment variable then click on new tab. In variable name write classpath and
in variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;

Example to connect to the mysql database


For connecting java application with the mysql database, you need to follow 5 steps to
perform database connectivity.
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the
database, localhost is the server name on which mysql is running, we may also use
IP address, 3306 is the port number and sonoo is the database name. We may use
any database, in such case, you need to replace the sonoo with your database name.
3. Username: The default username for the mysql database is root.

13

4. Password: Password is given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
1.
2.
3.

create database sonoo;


use sonoo;
create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql


database
In this example, sonoo is the database name, root is the username and password.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.

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/sonoo","root","root");
//here sonoo is database name, root is username and password
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);}
}
}
The above example will fetch all the records of emp table.
To connect java application with the mysql database mysqlconnector.jar file is required to be
loaded.

Two ways to load the jar file:


1. paste the mysqlconnector.jar file in jre/lib/ext folder
2. set classpath

14

1) paste the mysqlconnector.jar file in JRE/lib/ext folder:


Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.

2) set classpath:
There are two ways to set the classpath:
temporary

permament

How to set the temporary classpath


1.

open comman prompt and write:


C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

How to set the permanent classpath


Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending
mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;

Connectivity with Access without DSN


There are two ways to connect java application with the access database.
1. Without DSN (Data Source Name)
2. With DSN
Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic only
for knowledge.

Example to Connect Java Application with access


without DSN
In this example, we are going to connect the java program with the access database. In
such case, we have created the login table in the access database. There is only one column
in the table named name. Let's get all the name of the login table.
1.
2.

import java.sql.*;
class Test{

15

3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.

public static void main(String ar[]){


try{
String database="student.mdb";//Here database exists in the current directory
String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};
DBQ=" + database + ";DriverID=22;READONLY=true";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");
while(rs.next()){
System.out.println(rs.getString(1));
}
}catch(Exception ee){System.out.println(ee);}
}}

Example to Connect Java Application with access with


DSN
Connectivity with type1 driver is not considered good. To connect java application with
type1 driver, create DSN first, here we are assuming your dsn name is mydsn.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String url="jdbc:odbc:mydsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");
while(rs.next()){
System.out.println(rs.getString(1));
}
}catch(Exception ee){System.out.println(ee);}
}}

16