0% found this document useful (0 votes)
0 views

jdbc

JDBC (Java Database Connectivity) is a Java API that allows access to tabular data in relational databases across various platforms. It provides a standard interface for connecting to databases, executing SQL statements, and managing records, with four types of JDBC drivers available for different use cases. The document also outlines the installation process, database configuration, and basic operations such as establishing connections, executing queries, and handling exceptions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

jdbc

JDBC (Java Database Connectivity) is a Java API that allows access to tabular data in relational databases across various platforms. It provides a standard interface for connecting to databases, executing SQL statements, and managing records, with four types of JDBC drivers available for different use cases. The document also outlines the installation process, database configuration, and basic operations such as establishing connections, executing queries, and handling exceptions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

JDBC

JDBC is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.
JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

Why to Learn 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.

Applications of JDBC
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 Server Pages (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.

The JDBC 4.0 Packages


The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC version at the time
of writing this tutorial. It offers the main classes for interacting with your data sources.
The new features in these packages include changes in the following areas −
 Automatic database driver loading.
 Exception handling improvements.
 Enhanced BLOB/CLOB functionality.
 Connection and statement interface enhancements.
 National character set support.
 SQL ROWID access.
 SQL 2003 XML data type support.
 Annotations.
What is JDBC Driver?
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to interact with
it by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementations are done in third-party drivers. Third party vendors
implements the java.sql.Driver interface in their database driver.

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


In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique
to the database. These drivers are 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


In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a 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.

Type 4: 100% Pure Java


In a Type 4 driver, a pure Java-based driver communicates directly with the 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.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.

Which Driver should be used?


If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred
driver type is4.
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.

JDBC( Java DatabaseConnectivity):

The first thing you need to do is check that you are set up properly. This involves the
following steps:
1. Install Java and JDBC on your machine.
To install both the Java tm platform and the JDBC API, simply follow the instructions for
downloading the latest release of the JDK tm (Java Development Kit tm ). When you download
the JDK, you will get JDBC as well.

2. Install a driver on your machine.


Your driver should include instructions for installing it. For JDBC drivers written for specific
DBMSs, installation consists of just copying the driver onto your machine; there is no special
configuration needed.
The JDBC-ODBC Bridge driver is not quite as easy to set up. If you download JDK, you will
automatically get the JDBC-ODBC Bridge driver, which does not itself require any special
configuration. ODBC, however, does. If you do not already have ODBC on your machine, you
will need to see your ODBC driver vendor for information on installation and configuration.

3. Install your DBMS if needed.


If you do not already have a DBMS installed, you will need to follow the vendor's instructions
for installation. Most users will have a DBMS installed and will be working with an established
database.

Configuring Database:
Configuring a database is not at all difficult, but it requires special permissions and is normally
done by a database administrator.

First, open the control panel. You might find "Administrative tools" select it, again you may
find shortcut for "Data Sources (ODBC)". When you open the ―Data Source (ODBC)" 32bit
ODBC‖ icon, you‘ll see a "ODBC Data Source Administrator" dialog window with a number
of tabs, including ―User DSN,‖ ―System DSN,‖ ―File DSN,‖ etc., in which ―DSN‖ means ―Data
Source Name.‖ Select ―System DSN,‖. and add a new entry there, Select appropriate driver
for the data source or directory where database lives. You can name the entry anything you
want, assume here we are giving our data source name as"MySource".

JDBC Database Access

JDBC was designed to keep simple things simple. This means that the JDBC API makes everyday
database tasks, like simple SELECT statements, very easy.
Import a package java.sql.* : This package provides you set of all classes that enables a
network interface between the front end and back end database.
• DriverManager will create a Connectionobject.
• java.sql.Connection interface represents a connection with a specific database. Methods of
connection is close(), creatStatement(), prepareStatement(), commit(), close() and
prepareCall()
• Statement interface used to interact with database via the execution of SQL statements.
Methods of this interface are executeQuery(), executeUpdate(), execute() andgetResultSet().
• A ResultSet is returned when you execute an SQL statement. It maintains a pointer to a row
within the tablur results. Mehods of this interface are next(), getBoolean(), getByte(),
getDouble(), getString() close() andgetInt().

Establishing a Connection
The first thing you need to do is establish a connection with the DBMS you want to use. This
involves two
steps: (1) loading the driver and (2) making the connection.

Loading Drivers: Loading the driver or drivers you want to use is very simple and involves
just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the
following code will load it
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use.Forinstance, if
the class name is jdbc.DriverXYZ , you would load the driver with the following line of
code:
Class.forName("jdbc.DriverXYZ");
Making the Connection: The second step in establishing a connection is to have the
appropriate driver connect to the DBMS. The following line of code illustrates the general idea:
Connection con = DriverManager.getConnection(url,"myLogin", "myPassword");
If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: .
The rest of the URL is generally your data source name or database system. So, if you are using
ODBC to access an ODBC data source called "MySource, " for example, your JDBC URL
could be jdbc:odbc:MySource . In place of " myLogin " you put the name you use to log in to
the DBMS; in place of " myPassword " you put your password for the DBMS. So if you log in
to your DBMS with a login name of " scott " and a password of "tiger" just these two lines of
code will establish aconnection:
String url = "jdbc:odbc:MySource";
Connection con = DriverManager.getConnection(url, "scott", "tiger");
The connection returned by the method DriverManager.getConnection is an open connection
you can use to create JDBC statements that pass your SQL statements to the DBMS. In the
previous example, con is an open connection, and we will use it in the dorth coming examples.

Creating JDBC Statements


A Statement object is what sends your SQL statement to the DBMS. You simply create a
Statement object and then execute it, supplying the appropriate execute method with the SQL
statement you want to send. For a SELECT statement, the method to use is executeQuery . For
statements that create or modify tables, the method to use is executeUpdate .
It takes an instance of an active connection to create a Statement object. In the following
example, we use our Connection object con to create the Statement object stmt :
Statement stmt = con.createStatement();
At this point stmt exists, but it does not have an SQL statement to pass on to the DBMS. We
need to supply that to the method we use to execute stmt.
For example, in the following code fragment, we supply executeUpdate with the SQL
statement from the example above:
stmt.executeUpdate("CREATE TABLE STUDENT " +
"(S_NAME VARCHAR(32), S_ID INTEGER, COURSE VARCHAR2(10), YEAR
VARCHAR2(3)‖);
Since the SQL statement will not quite fit on one line on the page, we have split it
into two strings concatenated by a plus sign (+) so that it will compile. ExecutingStatements.
Statements that create a table, alter a table, or drop a table are all examples of DDL statements
and are executed with the method executeUpdate. The method executeUpdate is also used to
execute SQL statements that update a table. In practice, executeUpdate is used far more often
to update tables than it is to create them because a table is created once but may be updated
manytimes.
The method used most often for executing SQL statements is executeQuery . This method is
used to execute SELECT statements, which comprise the vast majority of SQL statements.

Entering Data into a Table


We have shown how to create the table STUDENT by specifying the names of the columns
and the data types to be stored in those columns, but this only sets up the structure of the table.
The table does not yet contain any data. We will enter our data into the table one row at a time,
supplying the information to be stored in each column of that row. Note that the values to be
inserted into the columns are listed in the same order that the columns were declared when the
table was created, which is the default order.

The following code inserts one row of data,


Statement stmt = con.createStatement();
stmt.executeUpdate( "INSERT INTO STUDENT VALUES ('xStudent', 501, ‗
B.Tech‘,‘IV‘)");
Note that we use single quotation marks around the student name because it is nested within
double quotation marks. For most DBMSs, the general rule is to alternate double
quotation marks and single quotation marks to indicatenesting.
The code that follows inserts a second row into the table STUDENT . Note that we can just
reuse the Statement object stmt rather than having to create a new one for each execution.
stmt.executeUpdate("INSERT INTO STUDENT " + "VALUES ('yStudent', 502,
‗B.Tech‘.‘III‘)");

Getting Data from a Table


Now that the table STUDENT has values in it, we can write a SELECT statement to access
those values. The star (*) in the following SQL statement indicates that all columns should be
selected. Since there is no WHERE clause to narrow down the rows from which to select, the
following SQL statement selects the whole table:
SQL> SELECT * FROM STUDENT;
Retrieving Values from Result Sets
We now show how you send the above SELECT statements from a program written in the Java
programming language and how you get the results we showed.

JDBC returns results in a ResultSet object, so we need to declare an instance of the class
ResultSet to hold our results. The following code demonstrates declaring the ResultSet object
rs and assigning the results of our earlier query toit:
ResultSet rs = stmt.executeQuery( "SELECT S_NAME, YEAR FROM STUDENT");
The following code accesses the values stored in the current row of rs. Each time the method
next is invoked, the next row becomes the current row, and the loop continues until there are
no more rows in rs .
String query = "SELECT COF_NAME, PRICE FROM STUDENT";
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
String s = rs.getString("S_NAME");
Integer i = rs.getInt("S_ID");
String c = rs.getString("COURSE");
String y = rs.getString(―YEAR‖);
System.out.println(i + " " + s + " " + c + " " + y);
}

Updating Tables
Suppose that after a period of time we want update the YEAR column in the table STUDENT.
The SQL statement to update one row might look likethis:
String updateString = "UPDATE STUDENT " +
"SET YEAR = IV WHERE S-NAME LIKE 'yStudent'";
Using the Statement object stmt , this JDBC code executes the SQL statement contained in
updateString :
stmt.executeUpdate(updateString);
Using try and catch Blocks:
Something else all the sample applications include is try and catch blocks. These are the Java
programming language's mechanism for handling exceptions. Java requires that when a method
throws an exception, there be some mechanism to handle it. Generally a catch block will catch
the exception and specify what happens (which you may choose to be nothing). In the sample
code, we use two try blocks and two catch blocks. The first try block contains the method
Class.forName, from the java.lang package. This method throws a ClassNotFoundException,
so the catch block immediately following it deals with that exception. The second try block
contains JDBC methods, which all throw SQLExceptions, so one catch block at the end of the
application can handle all of the rest of the exceptions that might be thrown because they
will all be SQLExceptionobjects.
Retrieving Exceptions
JDBC lets you see the warnings and exceptions generated by your DBMS and by the Java
compiler. To see exceptions, you can have a catch block print them out. For example, the
following two catch blocks from the sample code print out a message explaining the exception:
Try
{
// Code that could generate an exception goes here.
// If an exception is generated, the catch block below
// will print out information about it.
} catch(SQLException ex)
{
System.err.println("SQLException: " + ex.getMessage());
}
Java Program to Join Contents of More than One Table & Display in JDBC:

Java supports many databases and for each database, we need to have their respective jar files to be placed in
the build path to proceed for JDBC connectivity. First, need to decide, which database we are using and
accordingly, we need to add the jars. For other databases like Progress, Cassandra, etc also we have jars and
need to include them in the build path. There are different kinds of joins available in MySQL and depends
upon the requirement, we can frame queries.
Join is a join that provides the facility to connect two tables are merged with each other according to a field
that is common and creates a new virtual table.
 NATURAL JOIN: It is a type of join that retrieves data within specified tables to a specific field that is
matched.
 NATURAL LEFT JOIN: In this operation, both tables are merged with each other according to common
fields but the priority is given to the first table in the database.
 NATURAL RIGHT JOIN: It also the same as Natural left join but it retrieves the data from the second
table in the database.

MySQL tables that are used in code:


First table
CREATE TABLE `studentsdetails` (
`id` int(6) unsigned NOT NULL,
`Name` varchar(50) NOT NULL,
`caste` varchar(10) NOT NULL,
`NeetMarks` int(11) NOT NULL,
`gender` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Second table
CREATE TABLE `studentspersonaldetails` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(30) NOT NULL,
`Address` varchar(30) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`reg_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
In both tables, “Name” is the common column. 1st table specifies Gender, NeetMarks, Caste, etc whereas 2nd
table specifies the address, email, etc. Now only necessity is to create an SQL query to join the table which is
as follows:
SELECT * FROM " + "studentsdetails" + " NATURAL JOIN " + "studentspersonaldetails"
Now as this query is executed it retrieves data within specified tables to a specific field is matched, it will
match records in both tables depends upon “Name” column, implementing the Natural join concept in play.
Now the program depends upon the data present in both tables and for matching values of “Name” column in
both tables to get the desired output.
Implementation: Now executing the above query command with the help of the below program as per
Natural Join.
 Java

// Java Program to Join Contents


// of More than One Table & Display in JDBC

// Step 1: Importing DB files

// Provides the API for accessing and processing


// data stored in a data source
import java.sql.*;

// Class for Joining of multiple tables


public class GFG {

// Main driver method


public static void main(String[] args)
{

// Display message
System.out.println(
"Joining 2 MySQL tables using Natural Join");

// DB 'Connection' object of Connection class


Connection con = null;

// Try block to check exceptions


try {
// Step 2: Load and register drivers

// Loading driver
// Jars(relevant) or mysql-connector-java-8.0.22
// in build path of project
Class.forName("com.mysql.cj.jdbc.Driver");

// Registering driver

// test is database name here


// serverTimezone=UTC, if not provided we will
// have java.sql.SQLException
// Credentials here are root/""
// i.e. username is root
// password is ""

// Step 3: Establishing a connection


con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?serverTimezone=UTC",
"root", "");

// Try block to check java exceptions


try {

// Step 4: Write a statement


// Join
Statement st = con.createStatement();
// Combining two tables in query using
// NATURAL JOIN studentsdetails columns :
// Name,caste,NeetMarks,gender
// studentspersonaldetails columns :
// Name,Address,email

// In both tables, connecting columns are


// Name Name is taken Here res will have the
// data from
// both studentsdetails and
// studentspersonaldetails whenever "Name"
// in both tables are matched join
ResultSet res = st.executeQuery(
"SELECT *FROM "
+ "studentsdetails"
+ " NATURAL JOIN "
+ "studentspersonaldetails");

// Step 5: Execute the query


System.out.println(" StuName"
+ " Gender"
+ " Caste "
+ "Neet Marks"
+ " Email");

// Step 6: Process the statements


// Iterate the resultset and retrieve the
// required fields
while (res.next()) {
String name = res.getString("Name");
String gender = res.getString("gender");
String caste = res.getString("caste");
String neetMarks
= res.getString("NeetMarks");
String email = res.getString("email");

// Beautification of output
System.out.format(
"%10s%10s%10s%10s%20s\n", name,
gender, caste, neetMarks, email);
}

// Step 7: Close the connection


con.close();
}

// Catch bloack to handle DB exceptions


catch (SQLException s) {

// If there is error in SQL query, this


// exception occurs
System.out.println(
"SQL statement is not executed!");
}

// Catch bloack to handle generic java


// exceptions
}
catch (Exception e) {

// General exception apart from SQLException are


// caught here
e.printStackTrace();
}
}
}

Output :
Transaction Processing by JDBC:
Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL
statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction
fails.
To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default,
use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you
turn off auto-commit. You can pass a boolean true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn off auto-commit −
conn.setAutoCommit(false);
Commit & Rollback
Once you are done with your changes and you want to commit the changes then call commit() method on
connection object as follows −
conn.commit( );
Otherwise, to roll back updates to the database made using the Connection named conn, use the following code

conn.rollback( );
The following example illustrates the use of a commit and rollback object −
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback();
}
In this case, none of the above INSERT statement would success and everything would be rolled back.
Using Savepoints

The new JDBC 3.0 Savepoint interface gives you the additional transactional control. Most modern
DBMS, support savepoints within their environments such as Oracle's PL/SQL.
When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a
savepoint, you can use the rollback method to undo either all the changes or only the changes made after the
savepoint.
The Connection object has two new methods that help you manage savepoints −
 setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object.
 releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint
object as a parameter. This object is usually a savepoint generated by the setSavepoint() method.
There is one rollback (String savepointName) method, which rolls back work to the specified savepoint.
The following example illustrates the use of a Savepoint object –

try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();

//set a Savepoint
Savepoint savepoint1 = conn.setSavepoint("Savepoint1");
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Tez')";
stmt.executeUpdate(SQL);
// If there is no error, commit the changes.
conn.commit();

}catch(SQLException se){
// If there is any error.
conn.rollback(savepoint1);
}
In this case, none of the above INSERT statement would success and everything would be rolled back.
Stored Procedures in Java DB:
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task, and
they are used to encapsulate a set of operations or queries to execute on a database server. For example,
operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures
executed by application code. Stored procedures can be compiled and executed with different parameters and
results, and they can have any combination of input, output, and input/output parameters.

Note that stored procedures are supported by most DBMSs, but there is a fair amount of variation in their
syntax and capabilities. Consequently, the tutorial contains two
samples, StoredProcedureJavaDBSample.java and StoredProcedureMySQLSample.java, that demonstrate how
to create stored procedures in Java DB and MySQL, respectively.

Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the
CallableStatement object, which would be used to execute a call to a database stored procedure.
Creating CallableStatement Object
Let us write stored procedure for MySQL as follows to create it in EMP database.
DELIMITER $$

DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$


CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$

DELIMITER ;
Three types of parameters exist − IN, OUT, and INOUT. The PreparedStatement object only uses the IN
parameter. The CallableStatement object can use all the three.
Here are the definitions of each −

Parameter Description

IN A parameter whose value is unknown when the SQL statement is created. You
bind values to IN parameters with the setXXX() methods.
OUT A parameter whose value is supplied by the SQL statement it returns. You
retrieve values from the OUT parameters with the getXXX() methods.

INOUT A parameter that provides both input and output values. You bind variables with
the setXXX() methods and retrieve values with the getXXX() methods.

The following code snippet shows how to employ the Connection.prepareCall() method to instantiate
a CallableStatement object based on the preceding stored procedure −
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
The String variable SQL represents the stored procedure, with parameter placeholders.
Using CallableStatement objects is much like using PreparedStatement objects. You must bind values to all the
parameters before executing the statement, or you will receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object;
use the setXXX() method that corresponds to the Java data type you are binding.
When you use OUT and INOUT parameters, you must employ an additional CallableStatement method,
registerOutParameter(). The registerOutParameter() method binds the JDBC data type to the data type the
stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate
getXXX() method. This method casts the retrieved value of SQL type to a Java data type.
Closing CallableStatement Object
Just as you close other Statement object, for the same reason you should also close the CallableStatement
object.
A simple call to the close() method will do the job. If you close the Connection object first, it will close the
CallableStatement object as well. However, you should always explicitly close the CallableStatement object to
ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
cstmt.close();
}
JDBC SQL Escape Syntax
The escape syntax gives you the flexibility to use database specific features unavailable to you by using
standard JDBC methods and properties.
The general SQL escape syntax format is as follows −
{keyword 'parameters'}
Here are the following escape sequences, which you would find very useful while performing the JDBC
programming −
d, t, ts Keywords
They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the
same way. This escape syntax tells the driver to render the date or time in the target database's format. For
Example −
{d 'yyyy-mm-dd'}
Where yyyy = year, mm = month; dd = date. Using this syntax {d '2009-09-03'} is March 9, 2009.
Here is a simple example showing how to INSERT date in a table −
//Create a Statement object
stmt = conn.createStatement();
//Insert data ==> ID, First Name, Last Name, DOB
String sql="INSERT INTO STUDENTS VALUES" +
"(100,'Zara','Ali', {d '2001-12-16'})";

stmt.executeUpdate(sql);
Similarly, you can use one of the following two syntaxes, either t or ts −
{t 'hh:mm:ss'}
Where hh = hour; mm = minute; ss = second. Using this syntax {t '13:30:29'} is 1:30:29 PM.
{ts 'yyyy-mm-dd hh:mm:ss'}
This is combined syntax of the above two syntax for 'd' and 't' to represent timestamp.
escape Keyword
This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %,
which matches zero or more characters. For example −
String sql = "SELECT symbol FROM MathSymbols
WHERE symbol LIKE '\%' {escape '\'}";
stmt.execute(sql);
If you use the backslash character (\) as the escape character, you also have to use two backslash characters in
your Java String literal, because the backslash is also a Java escape character.
fn Keyword
This keyword represents scalar functions used in a DBMS. For example, you can use SQL function length to
get the length of a string −
{fn length('Hello World')}
This returns 11, the length of the character string 'Hello World'.
call Keyword
This keyword is used to call the stored procedures. For example, for a stored procedure requiring an IN
parameter, use the following syntax −
{call my_procedure(?)};
For a stored procedure requiring an IN parameter and returning an OUT parameter, use the following syntax −
{? = call my_procedure(?)};
oj Keyword
This keyword is used to signify outer joins. The syntax is as follows −
{oj outer-join}
Where outer-join = table {LEFT|RIGHT|FULL} OUTERJOIN {table | outer-join} on search-condition. For
example −
String sql = "SELECT Employees
FROM {oj ThisTable RIGHT
OUTER JOIN ThatTable on id = '100'}";
stmt.execute(sql);

You might also like