Java Database Connection
Java Database Connection
Java Database Connection
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.
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
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 −
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 −
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.
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:
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 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:
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:
Disadvantage:
throws SQLException
Statement stmt=con.createStatement();
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.
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
Method Description
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();
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());
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.*;
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
(“getMaxstatementLength:”+dbmd.getMaxStatementLength() +”\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
ResultSetMetaData rsmd=rs.getMetaData();
//ResuleSetMetaDataTest
import java.sql.*;
import java.util.*;
//read inputs
String tname=sc.next();
Class.forName(“oracle.jdbc.driver.OracleDriver”) ;
Connection
cn=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:oracl”,”scott”,”tiger”);
Statement st=cn.createStatement();
ResultSetMetaData rsmd=rs.getMetaData();
int colcnt=rsmd.getColumnCount();
for(int i=1;i<=colcnt;i++)
System.out.print (rsmd.getColumnLabel(i)+”\t\t” ) ;
System.out.println(“\n”);
for(int i=1;i<=colcnt;++i)
System.out.print (rsmd.getColumnTypeName(i)+”\t”);
}
System.out.println(“\n”);
while(rs.next())
System.out.println(rs.getString(1)+”\t\t”+rs.getString(2)+”\t\
t”+rs.getString(3));
}*/
rs.close() ;
st.close() ;
cn.close();