Unit 6
Unit 6
Applications of JDBC
JDBC enables you to create Java applications that handle the following three programming tasks:
Make a connection to a data source, such as a database.
Send database queries and update statements.
Retrieve and process the database results that were returned in response to your query.
JDBC Architecture
Application
Applications in JDBC architecture are java applications like applets or servlet that communicates
with databases.
JDBC API
The JDBC API is an Application Programming Interface used to create Databases, execute SQL
queries and retrieve results.
JDBC API uses classes and interfaces to connect with databases.
Some of the important classes includes DriverManager class, and some important interfaces are
Connection, PreparedStatement and ResultSet etc.
DriverManager
DriverManager class in the JDBC architecture is used to establish a connection between Java
applications and databases. Using the getConnection method of this class a connection is
established between the Java application and data sources.
JDBC Drivers
JDBC drivers are used to connecting with data sources. All databases like Oracle, MSSQL, MYSQL,
etc. have their drivers, and to connect with these databases we need to load their specific drivers.
Class is a java class used to load drivers.
Class.forName() method is used to load drivers in JDBC architecture.
Data Sources
Data Sources in the JDBC architecture are the databases that we can connect using this API. These are
the sources where data is stored and used by Java applications. JDBC API helps to connect various
databases like Oracle, MYSQL, MSSQL, PostgreSQL, etc.
Two-tier Architecture
This architecture helps java program or application to directly communicate with the database.
It needs a JDBC driver to communicate with a specific database.
Query is sent by the user to the database and results are received back by the user.
The database may be present on the same machine or any remote machine connected via a
network. This approach is called client-server architecture.
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:
Advantages
This driver software is built-in with JDK so no need to install separately.
It is a database independent driver.
Disadvantages
As a common driver is used in order to interact with different databases, the data transferred
through this driver is not so secured.
The ODBC bridge driver is needed to be installed in individual client machines.
Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
Where oracle is the database, thin is the driver, @localhost is the IP Address where the
database is stored, 1521 is the port number, and xe is the service provider. All three parameters
are of String type and the programmer should declare them before calling the function
Here, con is a reference to the Connection interface that we used in the previous step.
Approach I - Class.forName()
The most common approach to register a driver is to use Java's Class.forName() method, to
dynamically load the driver's class file into memory, which automatically registers it.
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
}
Approach II - DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the
static DriverManager.registerDriver() method.
The following example uses registerDriver() to register the Oracle driver −
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
}
Method Description
1) void registerDriver ( is used to register the given driver with DriverManager. No action
Driver driver): is performed by the method when the given driver is already
registered.
2) void deregisterDriver ( is used to deregister the given driver (drop the driver from the
Driver driver): 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 is used to establish the connection with the specified url,
getConnection(String username, and password. The SQLException is thrown when the
url,String userName,String corresponding Driver class of the given database is not registered
password) throws with the DriverManager.
SQLException:
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.aster Internet Connection
2) public void commit(): saves the changes made since the previous commit/rollback is permanent.
3) public void rollback(): Drops all changes made since the previous commit/rollback.
4) public void close(): closes the connection and Releases a JDBC resources immediately.
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.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table.
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 row): is used to move the cursor to the specified row number in the
ResultSet object.
6) public int getInt(int columnIndex): is used to return the data of specified column index of the
current row as int.
7) public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.
8) public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.
9) public String getString(String is used to return the data of specified column name of the
columnName): current row as String.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
Example:
SQL> CREATE TABLE emp (
id int,
fname varchar(255),
lname varchar(255),
);
Syntax:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
SQL> insert into emp values (1,'akshay','somwanshi');
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Advantages of PreparedStatement
When PreparedStatement is created, the SQL query is passed as a parameter. This Prepared
Statement contains a pre-compiled SQL query, so when the PreparedStatement is executed,
DBMS can just run the query instead of first compiling it.
We can use the same PreparedStatement and supply with different parameters at the time of
execution.
2. Prepare Statement
Instead of hardcoding queries like,
select * from students where age>10 and name ='Arrow'
Methods of PreparedStatement:
setInt(int, int): This method can be used to set integer value at the given parameter index.
setString(int, string): This method can be used to set string value at the given parameter
index.
setFloat(int, float): This method can be used to set float value at the given parameter index.
setDouble(int, double): This method can be used to set a double value at the given
parameter index.
executeUpdate(): This method can be used to create, drop, insert, update, delete etc. It
returns int type.
executeQuery(): It returns an instance of ResultSet when a select query is executed.
import java.util.*;
import java.sql.*;
class Program4
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","123");
pstmt.setInt(1,roll);
pstmt.setString(2,name);
pstmt.setInt(3,marks);
int x=pstmt.executeUpdate();
System.out.println(" No of Rows Inserted into table:"+x);
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
import java.util.*;
import java.sql.*;
class Program6
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","123");
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 it returns the column type name for the
index)throws SQLException specified index.
Example:
import java.sql.*;
class Program5{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","123");
CallableStatement
The CallableStatement interface provides methods to execute the stored procedures.
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(?, ?, ?)}");
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");
cstmt.execute();
To call the stored procedure, you need to create it in the database. Here, we are assuming that stored
procedure looks like this.
create or replace procedure "INSERTR" (roll in number, name in varchar, marks in number)
is
begin
insert into StudArrow values(roll,name,marks);
end;
/
Example
In this example, we are going to call the stored procedure MyProcedure that receives rollno, name
and marks as the parameter and inserts it into the table stud. Note that you need to create the stud
table as well to run this application.
import java.sql.*;
import java.util.*;
public class Sample
{
public static void main(String[] args)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","123");
stmt.setInt(1,roll);
stmt.setString(2,name);
stmt.setInt(3,marks);
stmt.execute();
System.out.println("success");
}
catch(Exception e)
{
System.out.println(e);
}
}
}