You are on page 1of 14

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, which is explained below:

Type 1: JDBC-ODBC Bridge Driver:


In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that
represents the target database.

When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.

The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC-Native API: (Native 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 typically provided by the database vendors and used in the same
manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client
machine.

If we change the Database we have to change the native API as it is specific to a database and
they are mostly obsolete now but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java: (Network


Protocol Driver)
In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use
standard network sockets to communicate with an middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's configuration
in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Type 4: 100% pure Java: ( Thin Driver )


In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.
Which Driver should be used?
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.

If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.

Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your
database.

The type 1 driver is not considered a deployment-level driver and is typically used for
development and testing purposes only.

Connecting with oracle database: (Technique-1):

import java.sql.*;
class DBConnect1
{
public static void main(String[] args)throws Exception
{
//creating driver object
Driver drv = new oracle.jdbc.driver.OracleDriver();

//register driver object with DriverManager


DriverManager.registerDriver(drv);

//getting connection object


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

if( con != null )


System.out.println("connected");
else
System.out.println("not connected");
}
}

Connecting with oracle database: ( Technique – 2 ):


import java.sql.*;
class DBConnect2
{
public static void main(String[] args)throws Exception
{
//here forName() method will load .class file into JVM's memory.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","tiger");

if( con != null )


System.out.println("connected...");
else
System.out.println("not connected..");
}
}

Connecting with oracle database using properties file: ( Technique – 3 )

Drv.properties:-
driver.class = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin:@localhost:1521:xe
username = system
password = tiger

DBConnect.java:-
import java.sql.*;
import java.util.*; //Properties
import java.io.*; //FileInputStream
class DBConnect
{
public static void main(String[] args)throws Exception
{
//create Properties class object
Properties props = new Properties();

//create FileInputStream object to read data from drv.properties


FileInputStream fis = new FileInputStream("drv.properties");

//load all the properties from fis into props.


props.load(fis);

//here forName() method will load .class file into JVM's memory.
Class.forName(props.getProperty("driver.class"));
Connection con =
DriverManager.getConnection(props.getProperty("url"),props.getProperty("username"),props.get
Property("password"));

if( con != null )


System.out.println("connected...");
else
System.out.println("not connected..");
}
}

Creating Table in database from java application:


import java.sql.*;

class DBCreateTableDemo
{
public static void main(String[] args)throws Exception
{
Driver drv = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(drv);
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","tiger");

String vsql = "create table product (pid number(4) primary key,pname


varchar2(20),price number(10,2))";
Statement stmt = con.createStatement();
int n = stmt.executeUpdate(vsql);

System.out.print("n:" + n);

con.close();

}
}

Inserting Data into table using PreparedStatement:-


import java.sql.*;
import java.util.*;

class DBInsertDemo
{
public static void main(String[] args)throws Exception
{
int id=0;
String name="";
double price=0.0;

Driver drv = new oracle.jdbc.driver.OracleDriver();


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

String vsql = "insert into product values(?,?,?)";

PreparedStatement pstmt = con.prepareStatement(vsql);

Scanner sc = new Scanner(System.in);


System.out.print("Enter how records:");
int nr = sc.nextInt();

for(int i=1;i<=nr;i++){
System.out.print("Enter product id:");
id = sc.nextInt();
System.out.print("Enter product name:");
name = sc.next() + sc.nextLine();
System.out.print("Enter product price:");
price = sc.nextDouble();
//storing data into positional parameters
pstmt.setInt(1,id);
pstmt.setString(2,name);
pstmt.setDouble(3,price);

//execute the query


pstmt.executeUpdate();
}
con.close();

}
}

Updating table data in the database from java application:


import java.sql.*;
import java.util.*;

class DBUpdateDemo
{
public static void main(String[] args)throws Exception
{
int id=0;
String name="";

Driver drv = new oracle.jdbc.driver.OracleDriver();


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

String vsql = "update product set pname= ? where pid = ?";

PreparedStatement pstmt = con.prepareStatement(vsql);

Scanner sc = new Scanner(System.in);


System.out.print("Enter product id to update:");
id = sc.nextInt();
System.out.print("Enter new product name to update:");
name = sc.next() + sc.nextLine();
//storing data into positional parameters
pstmt.setString(1,name);
pstmt.setInt(2,id);

//execute the query


pstmt.executeUpdate();

con.close();

}
}
Retrieving data from table using java application:-
import java.sql.*;
import java.util.*;

class DBRetrieveDemo
{
public static void main(String[] args)throws Exception
{
int id=0;
String name="";
double price=0.0;

Driver drv = new oracle.jdbc.driver.OracleDriver();


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

String vsql = "select * from product";

Statement stmt = con.createStatement();


ResultSet rs = stmt.executeQuery(vsql);
while( rs.next() ){
System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t" +
rs.getDouble(3));
}
con.close();
}
}

Example for scrollable and updatable resultset:-


import java.sql.*;
import java.util.*;

class ScrollableAndUpdatableRSDemo
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","hai");

String vsql = "select empid,empname,age,desig,salary from employee";


Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATA
BLE);
//retreiveing scrollable resultset
ResultSet rs = stmt.executeQuery(vsql);
System.out.println("Current row:" + rs.getRow());
System.out.println("Employee details:");
while(rs.next()){
System.out.println("id:" + rs.getInt(1));
System.out.println("name:" + rs.getString(2));
System.out.println("age:" + rs.getInt(3));
System.out.println("desig:" + rs.getString(4));
System.out.println("sal:" + rs.getDouble(6));
}

//moving to first row


rs.first();
rs.updateString(2,"Ramya");//updated only on column in rs
rs.updateRow();//updated entire row in DB

//moving to last row


rs.last();
rs.deleteRow();
con.close();
}
}

Display the description of a table using ResultSetMetaData:-


import java.sql.*;

class ResultSetMetaDataDemo
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","hai");

String vsql = "select * from employee";


Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(vsql);
ResultSetMetaData rsmd = rs.getMetaData();
int ccount = rsmd.getColumnCount();
System.out.println("total cols:" + ccount);
System.out.println("Name" + "\t" + "Type");
System.out.println("----" + "\t" + "----");

for(int i=1;i<=ccount;i++){
System.out.println(rsmd.getColumnName(i) + "\t" +
rsmd.getColumnTypeName(i));
}
con.close();
}
}

Storing Image into database:-

 First create table in the database like below:


Sql> Create table imagetable(id number(2) primary key, name varchar2(20), img BLOB);
ImageStoreDemo.java:

import java.sql.*;
import java.io.*;

class ImageStoreDBDemo
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","tiger");

String vsql = "insert into imagetable values(?,?,?)";

PreparedStatement pstmt = con.prepareStatement(vsql);

pstmt.setInt(1,1001);
pstmt.setString(2,"Flower1");

//read image from local system


FileInputStream fis = new FileInputStream("D:\\2018-19 even semister\\DWP
course\\section-1\\images\\flower1.jpg");

pstmt.setBinaryStream(3,fis,fis.available());
int n = pstmt.executeUpdate();

if( n > 0 )
System.out.println("Image stored successfully");

fis.close();

con.close();
}
}

Storing text file into database :-

 First create table in the database like below:


Sql> Create table filetable(id number(2) primary key, name varchar2(20), file CLOB);

import java.sql.*;
import java.io.*;

class ImageStoreDBDemo
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","tiger");

String vsql = "insert into filetable values(?,?,?)";

PreparedStatement pstmt = con.prepareStatement(vsql);

pstmt.setInt(1,1001);
pstmt.setString(2,"student");

File f=new File("d:\\myfile.txt");


FileReader fr=new FileReader(f);

ps.setCharacterStream(3,fr,(int)f.length());
int i=ps.executeUpdate();
System.out.println(i+" records affected");

con.close();
}
}

Retrieving Image from database :-


import java.sql.*;
import java.io.*;

class ImageRetrieveDBDemo
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","tiger");

String vsql = "select * from imagetable";

PreparedStatement pstmt = con.prepareStatement(vsql);

ResultSet rs = pstmt.executeQuery();

if( rs.next() ){
Blob b = rs.getBlob(3);
FileOutputStream fout = new FileOutputStream("1.jpg");
byte barr[] = b.getBytes(1,(int)b.length());
fout.write(barr);
fout.close();
}
con.close();
}
}

Retrieving text file data from database:


import java.sql.*;
import java.io.*;

class ImageRetrieveDBDemo
{
public static void main(String[] args)throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","tiger");
String vsql = "select * from filetable";

PreparedStatement pstmt = con.prepareStatement(vsql);

ResultSet rs = pstmt.executeQuery();

if( rs.next() ){
Clob c = rs.getClob(3);
FileWriter fw = new FileWriter("1.txt");
Reader r=c.getCharacterStream(); 
Int i;
While( (i = r.read()) != -1 ){
Fw.write((char)i);
}
System.out.println(“Successfully done”);
fw.close();
}
con.close();
}
}

You might also like