Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Database Connection

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

Introduction

JDBC or Java Database Connectivity is a Java API to connect and execute the query with the
database. It is a specification from Sun microsystems that provides a standard abstraction(API or
Protocol) for java applications to communicate with various databases. It provides the language with
java database connectivity standards. It is used to write programs required to access databases. JDBC,
along with the database driver, can access databases and spreadsheets. The enterprise data stored in a
relational database(RDB) can be accessed with the help of JDBC APIs.

What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.

 Making a connection to a database.

 Creating SQL or MySQL statements.

 Executing SQL or MySQL queries in the database.

 Viewing & Modifying the resulting records.

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows
for portable access to an underlying database. Java can be used to write different types of
executables, such as −

 Java Applications

 Java Applets

 Java Servlets

 Java ServerPages (JSPs)

 Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.

JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
DBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −

 JDBC API − This provides the application-to-JDBC Manager connection.


 JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.

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.

Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −

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.

 Driver − This interface handles the communications with the database server. You
will interact directly with Driver objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also abstracts the details associated
with working with Driver objects.

 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. It acts as an iterator to allow you to move through
its data.

 SQLException − This class handles any errors that occur in a database application.

Definition of JDBC(Java Database Connectivity)

JDBC is an API(Application programming interface) used in java programming to interact


with databases. The classes and interfaces of JDBC allow the application to send requests
made by users to the specified database.

Purpose of JDBC

Enterprise applications created using the JAVA EE technology need to interact with
databases to store application-specific information. So, interacting with a database requires
efficient database connectivity, which can be achieved by using the ODBC(Open database
connectivity) driver. This driver is used with JDBC to interact or communicate with various
kinds of databases such as Oracle, MS Access, Mysql, and SQL server database.

JDBC Driver
1. JDBC Drivers
1. JDBC-ODBC bridge driver
2. Native-API driver
3. Network Protocol driver
4. Thin driver
JDBC Driver is a software component that enables java application to interact with the database.
There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

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. This is now discouraged
because of thin driver.
In Java 8, the JDBC-ODBC Bridge has been removed.
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.

2) 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.
A
dvantage:
 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.

3) Network Protocol 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.
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.

4) Thin 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.
Advantage:

 Better performance than all other drivers.


 No software is required at client side or server side.

Disadvantage:

 Drivers depend on the Database.

Java Database Connectivity with 5 Step


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 to register the OracleDriver class


Here, Java program is loading oracle driver to esteblish database connection.
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) public static Connection getConnection(String url)throws SQLException

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

throws SQLException

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 to create the statement object

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
public ResultSet executeQuery(String sql)throws SQLException

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


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

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 to close connection

con.close();
Statement
 boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be
retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or
when you need to use the truly dynamic SQL.

 int executeUpdate(String SQL): Returns the number of rows affected by the


execution of the SQL statement. Use this method to execute SQL statements, for
which you expect to get a number of rows affected - for example, an INSERT,
UPDATE, or DELETE statement.
 ResultSet executeQuery(String SQL)− Returns a ResultSet object. Use this method
when you expect to get a result set, as you would with a SELECT statement.

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 index.
value)

public void setString(int paramIndex, String


sets the String value to the given parameter index.
value)

public void setFloat(int paramIndex, float


sets the float value to the given parameter index.
value)
public void setDouble(int paramIndex,
sets the double value to the given parameter index.
double value)

executes the query. It is used for create, drop, insert,


public int executeUpdate()
update, delete etc.

executes the select query. It returns an instance of


public ResultSet executeQuery()
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:

import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","s
ystem","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

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,"Sonoo");//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();
5. System.out.println(i+" records deleted");

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. }

Java CallableStatement Interface


CallableStatement interface is used to call the stored procedures and functions.

We can have business logic on the database by the use of stored procedures and functions
that will make the performance better because these are precompiled.

Suppose you need the get the age of the employee based on the date of birth, you may create
a function that receives date as the input and returns age of the employee as the output.

The CallableStatement interface provides methods to execute the stored procedures. Since
the JDBC API provides a stored procedure SQL escape syntax, you can call stored
procedures of all RDBMS in single standard way.

Creating a CallableStatement

You can create an object of the CallableStatement (interface) using the prepareCall()
method of the Connection interface. This method accepts a string variable representing a
query to call the stored procedure and returns a CallableStatement object.

A Callable statement can have input parameters, output parameters or both. To pass input
parameters to the procedure call you can use place holder and set values to these using the
setter methods (setInt(), setString(), setFloat()) provided by the CallableStatement interface.

Suppose you have a procedure name myProcedure in the database you can prepare a callable
statement as:

//Preparing a CallableStatement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");
Setting values to the input parameters

You can set values to the input parameters of the procedure call using the setter methods.

These accepts two arguments, one is an integer value representing the placement index of the
input parameter and, the other is a int or, String or, float etc… representing the value you
need to pass as input parameter to the procedure.

Note: Instead of index you can also pass the name of the parameter in String format.

cstmt.setString(1, "Raghav");
cstmt.setInt(2, 3000);
cstmt.setString(3, "Hyderabad");
Executing the Callable Statement

Once you have created the CallableStatement object you can execute it using one of the
execute() method.

cstmt.execute();

Example

Suppose we have a table named Employee in the MySQL database with the following data:

+---------+--------+----------------+
| Name | Salary | Location |
+---------+--------+----------------+
| Amit | 30000 | Hyderabad |
| Kalyan | 40000 | Vishakhapatnam |
| Renuka | 50000 | Delhi |
| Archana | 15000 | Mumbai |
+---------+--------+----------------+

And we have created a procedure named myProcedure to insert values in to this table as
shown below:

Create procedure myProcedure (IN name VARCHAR(30), IN sal INT, IN loc VARCHAR(45))
-> BEGIN
-> INSERT INTO Employee(Name, Salary, Location) VALUES (name, sal, loc);
-> END //

Following is a JDBC example which inserts new records into the Employee table by calling
the above created procedure, using a callable statement.

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class CallableStatementExample {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());

//Getting the connection


String mysqlUrl = "jdbc:mysql://localhost/testdb";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Preparing a CallableStateement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");

cstmt.setString(1, "Raghav");
cstmt.setInt(2, 3000);
cstmt.setString(3, "Hyderabad");

cstmt.setString(1, "Kalyan");
cstmt.setInt(2, 4000);
cstmt.setString(3, "Vishakhapatnam");

cstmt.setString(1, "Rukmini");
cstmt.setInt(2, 5000);
cstmt.setString(3, "Delhi");

cstmt.setString(1, "Archana");
cstmt.setInt(2, 15000);
cstmt.setString(3, "Mumbai");

cstmt.execute();
System.out.println("Rows inserted ....");
}
}

Data about data is called metadata. That means data about column names, data type names of
database software etc. JDBC supported Metadata programming areas follows:

1 Database Metadata

2 ResultSet Metadata

Database Metadata

By this programmer can get limitations and capabilities of underlying Database software like
database software name, versions, max chars in table, etc. Database- Metadata object means
it the object of a java class that implements java.sql. Database Metadata (interface).
Programmer call various methods on Database Metadata object to gather much information
about underlying database software.

DatabaseMetaDatadbmd=con.getMetaData();

Use

DatabaseMetaData programming is useful while developing GUI tools for Database software
like sqlyog, mysql front, etc.
JDBC Metadata Programming is in no way related to performing CURD operations on
database. It is given to gather additional details about database software and its tables. If
certain JDBC driver cannot retrieve certain information about database then it returns zero
“0” or “null” value while working with DatabaseMetaData object.

Example application

//DBMetaData.java

import java.io.*;

import java.sql.*;

public class DBMetaData

public static void main (String args[ ]) throws


SQLException,ClassNotFoundException

Class.forName(“Sun.jdbc.odbc.JdbcOdbcDrivet”) ;

Connection
con=DriverManager.getConnection(“jdbc:odbc:oradsn”,”scott”,”tiger”);

DatabaseMetaData dbmd=con.getMetaData();

System.out.println(“database version:”+dbmd.getDatabaseProductVersion()+”\
n”);

System.out.println(“database name:”+dbmd.getDatabaseProductName()+”\n”);

System.out.println(“sql keywords:” +dbmd.getSQLKeywords() +”\n”);

System.out.println(“numeric functions: “+dbmd.getNumericFunctions () +”\


n”) ;

System.out.println(“String functions: “+dbmd.getStringFunctions ()+”\n” );

System.out.println (“System functions:” +dbmd.getSystemFunctions()+”\n”) ;

System.out.println(“Searc string Escape:” +dbmd.getSearchStringEscape ()+”\


n”);
System.out.println (“getMaxRowSize: “+dbmd.getMaxRowSize()+”\n”);

System.out.println
(“getMaxstatementLength:”+dbmd.getMaxStatementLength() +”\n”);

System.out.println(“get maximum tables in a select


query:”+dbmd.getMaxTablesInSelect()+”\n”);

System.out.println(“get maximum length of table


name:”+dbmd.getMaxTableNameLength()+”\n”);

System.out.println(“jdbcapi version is :”+dbmd.getJDBCMajorVersion()+”\


n”);

ResultSetMetaData

It is used to gather more information about database table that is represented by JBDC
ResultSet object. It is used to get no of columns, column name, column data types, etc.,
information from database table.

ResultSetMetaData object means it is the object of JBDC driver supplied Java class that
implements java.sql.ResultSet.MetaData(interface). This object is very useful while
generating reports based on database table data; like progress report, sales report, etc.

Method calling

ResultSet rs =st.executeQuery(“select * from emp”);

ResultSetMetaData rsmd=rs.getMetaData();

//ResuleSetMetaDataTest

import java.sql.*;

import java.util.*;

public class ResultSetMetaDataTest

public static void main(String args[]) throws


SQLException,ClassNotFoundException

//read inputs

Scanner sc = new Scanner(System.in);

System.out.println(“Enter table name”);

String tname=sc.next();

//create jdbc connection

Class.forName(“oracle.jdbc.driver.OracleDriver”) ;

Connection
cn=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:oracl”,”scott”,”tiger”);

Statement st=cn.createStatement();

ResultSet rs=st.executeQuery (“select * from “+tname);

ResultSetMetaData rsmd=rs.getMetaData();

int colcnt=rsmd.getColumnCount();

//System.out.println(“Columns present in the table are:\n”) ;

for(int i=1;i<=colcnt;i++)

System.out.print (rsmd.getColumnLabel(i)+”\t\t” ) ;

System.out.println(“\n”);

//Systeml.out.println(“datatypes of the columns are:\n”);

for(int i=1;i<=colcnt;++i)

System.out.print (rsmd.getColumnTypeName(i)+”\t”);

}
System.out.println(“\n”);

//System.out.println(“records of the table are:\n”);

while(rs.next())

System.out.println(rs.getString(1)+”\t\t”+rs.getString(2)+”\t\
t”+rs.getString(3));

/*for (int i=1; i<=colcnt; ++i)

System.out.println(rs. getString(i) +”\ t “) ;

}*/

rs.close() ;

st.close() ;

cn.close();

You might also like