Java Datebase Connectivity
Java Datebase Connectivity
Java Datebase Connectivity
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 commonly associated with database usage:
JDBC Architecture:
Description:
1. Application: It is a java applet or a servlet that communicates with a data source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve results.
Some of the important classes and interfaces defined in JDBC API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific
drivers to effectively connect enterprise applications to databases.
4. JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that
intelligently communicates with the respective data source.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert
requests from Java programs to a protocol that the DBMS can understand. There are 4 types of JDBC
drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin 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.
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:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function calls.
o 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.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
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:
o No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o 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:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
Step 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.
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
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
To connect java application with the oracle database, we need to follow 5 following steps. In this example,
we are using Oracle 10g as the database. So we need to know following information for the oracle database:
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
4. Password: It is the password given by the user at the time of installing the oracle database.
Example to Connect Java Application with Oracle database
In this example, we are connecting to an Oracle database and getting data from emp table.
Here, system and oracle are the username and password of the Oracle database.
import java.sql.*;
class OracleCon
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","system",
"oracle");
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);
}
}
}
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, we need to replace the sonoo with our
database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password 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.
In this example, sonoo is the database name, root is the username and password both.
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"
);
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);
}
}
}
Connectivity with Access without DSN
There are two ways to connect java application with the access database.
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.
import java.sql.*;
class Test{
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.
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);
}
}
}
DriverManager class
The DriverManager class is the component of JDBC API and also a member of the java.sql package. The
DriverManager class acts as an interface between users and drivers. It keeps track of the drivers that are
available and handles establishing a connection between a database and the appropriate driver. It contains
all the appropriate methods to register and deregister the database driver class and to create a connection
between a Java application and the database. The DriverManager class maintains a list of Driver classes
that have registered themselves by calling the method DriverManager.registerDriver(). Note that before
interacting with a Database, it is a mandatory process to register the driver; otherwise, an exception is
thrown.
1) public static synchronized void is used to register the given driver with DriverManager. No
registerDriver(Driver driver): action is performed by the method when the given driver is
already registered.
2) public static synchronized void is used to deregister the given driver (drop the driver from
deregisterDriver(Driver driver): the list) with DriverManager. If the given driver has been
removed from the list, then no action is performed by the
method.
3) public static Connection getConnection(String is used to establish the connection with the specified url. The
url) throws SQLException: SQLException is thrown when the corresponding Driver class
of the given database is not registered with the
DriverManager.
4) public static Connection getConnection(String is used to establish the connection with the specified url,
url,String userName,String password) throws username, and password. The SQLException is thrown when
SQLException: the corresponding Driver class of the given database is not
registered with the DriverManager.
5) public static Driver getDriver(String url) Those drivers that understand the mentioned URL (present in
the parameter of the method) are returned by this method
provided those drivers are mentioned in the list of registered
drivers.
6) pubic static int getLoginTimeout() The duration of time a driver is allowed to wait in order to
establish a connection with the database is returned by this
method.
7) pubic static void setLoginTimeout (int sec) The method provides the time in seconds. sec mentioned in
the parameter is the maximum time that a driver is allowed
to wait in order to establish a connection with the database.
If 0 is passed in the parameter of this method, the driver will
have to wait infinitely while trying to establish the connection
with the database.
8) public static Connection getConnection A connection object is returned by this method after creating
(String URL, Properties prop) throws a connection to the database present at the mentioned URL,
SQLException which is the first parameter of this method. The second
parameter, which is "prop", fetches the authentication
details of the database (username and password.). Similar to
the other variation of the getConnection() method, this
method also throws the SQLException, when the
corresponding Driver class of the given database is not
registered with the DriverManager.
Connection interface
A Connection is a session between a Java application and a database. It helps to establish a connection with
the database.
1) public Statement createStatement(): creates a statement object that can be used to execute SQL
queries.
3) public void setAutoCommit(boolean status): is used to set the commit status. By default, it is true.
4) public void commit(): saves the changes made since the previous commit/rollback is permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement interface
The Statement interface provides methods to execute queries with the database. The statement interface
is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of
ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert,
update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before the
first row.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we
can make this object as updatable by:
1) public boolean next(): is used to move the cursor to the one row next from the current
position.
2) public boolean previous(): is used to move the cursor to the one row previous from the current
position.
3) public boolean first(): is used to move the cursor to the first row in result set object.
4) public boolean last(): is used to move the cursor to the last row in result set object.
5) public boolean absolute(int is used to move the cursor to the specified row number in the ResultSet
row): object.
6) public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet
object, it may be positive or negative.
7) public int getInt(int is used to return the data of specified column index of the current row
columnIndex): as int.
8) public int getInt(String is used to return the data of specified column name of the current row
columnName): as int.
9) public String getString(int is used to return the data of specified column index of the current row
columnIndex): as String.
10) public String getString(String is used to return the data of specified column name of the current row
columnName): as String.
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.
Example of parameterized query:
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.
The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement.
Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.
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)
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.
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","system","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);
}
}
}
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column type etc. ,
ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet
object.
Method Description
public int getColumnCount()throws SQLException it returns the total number of columns in the
ResultSet object.
public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.
public String getColumnTypeName(int index)throws it returns the column type name for the
SQLException specified index.
public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.
The getMetaData() method of Connection interface returns the object of DatabaseMetaData. Syntax:
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:Driver Name: Oracle JDBC Driver
Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production
import java.sql.*;
public class Proc {
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","oracle");
CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();
System.out.println("success");
}
}
Now check the table in the database, value is inserted in the user420 table.
Transaction represents a single unit of work. The ACID properties describes the transaction management
well. ACID stands for Atomicity, Consistency, isolation and durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another consistent state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the event of errors,
power loss etc.
Method Description
void setAutoCommit(boolean status) It is true bydefault means each transaction is committed bydefault.
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
}}
If you see the table emp400, you will see that 2 records has been added.
Batch Processing in JDBC
Instead of executing a single query, we can execute a batch (group) of queries. It makes the performance
fast. It is because when one sends multiple statements of SQL at once to the database, the communication
overhead is reduced significantly, as one is not communicating with the database frequently, which in turn
results to fast performance.
The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing.
Method Description
int[] executeBatch() The executeBatch() method begins the execution of all the
grouped together statements. The method returns an integer
array, and each of the element of the array represents the
updated count for respective update statement.
void clearBatch() The method removes all the statements that one has added
using the addBatch() method.
Let's see the simple example of batch processing in JDBC. It follows following steps:
import java.sql.*;
class FetchRecords{
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","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.addBatch("insert into user420 values(190,'abhi',40000)");
stmt.addBatch("insert into user420 values(191,'umesh',50000)");
If you see the table user420, two records have been added.