JDBC
JDBC
1
JDBC - Java Database Connectivity
stands for Java Data Base 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.
2
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.
3
• JDBC is similar to Microsoft’s ODBC (Open Data Base Connectivity). JDBC API
makes everyday database tasks like simple select statements very easy.
• The role of the JDBC is just to act like a wrapper to let you feed SQL requests to the
server.
• To access a database on the same machine, or a server on a LAN or on a server across the
Internet, JDBC can be used.
4
Talking to Databases
• A JDBC based application is insulated from the characteristics of specific
database engines
Java Application
JDBC
5
JDBC Concepts
• JDBC’s design is very similar to the design of ODBC
• Driver Manager
– Loads database drivers, and manages the connection between the application and the driver
• Driver
– Translates API calls into operations for a specific data source
• Connection
– A session between an application and a database.
• Statement
– An SQL Statement to perform a query or update operation
• Metadata
– Information about returned data, the database and the driver
• ResultSet
– Logical set of columns and rows returned by executing an SQL statement (resulting tuples: an
ordered set of data)
6
Steps during execution
• The following steps are executed when running a JDBC application
– Import the necessary classes
– Load the JDBC driver
– Identify the database source
– Allocate a “connection” object (create)
– Allocate a “Statement” object (create)
– Execute a query using the “Statement” object
– Retrieve data from the returned “ResultSet” object
– Close the “ResultSet” object
– Close the “Statement” object
– Close the “Connection” object
7
IMMEDIATE SOLUTIONS
JDBC Packages
• The JDBC API is contained in two packages.
• The first package is called java.sql and contains core Java data objects of the
JDBC API. java.sql is part of the J2SE
• These include Java data objects that provide the basic for connecting to the DBMS
and interacting with data stored in the DBMS.
Driver Creates
Manager Connection Creates Statement Creates ResultSet
SQL
Driver
Establish
Link to DB Result
(tuples)
Database
9
• While writing any database application, the following fundamental issues are
encountered :
• The first one is creating a database. we can either create the
database outside of Java, via tools which is supplied by the database
via SQL statements fed to the database from a Java program.
• The second one is connecting to an ODBC data source. It is registered with the ODBC
driver. We can use either JDBC to ODBC Bridge to connect to the data source in Java.
• The third one is inserting information into database. we can either
enter data outside of Java using database specific tools, or using
SQL statements sent by the Java program.
• The fourth is selectively retrieving information. we can use SQL
commands from Java to get results and then use Java to display or
manipulate that data.
10
Steps Involved in Basic JDBC Operations
Driver Manager
1. Load the JDBC driver class:
Class.forName(“driverName”); Driver
11
Two-Tier Database Access Model
• Java Application talks directly to the
database Application Space
Database
12
Three-Tier Database Access Model
• JDBC driver sends commands to a
middle tier, which in turn sends Application Space
commands to database. Java Application
• Results are sent back to the middle tier,
which communicates them back to the JDBC Driver
application.
SQL Result
Command Set
Application Server
(middle-tier)
Proprietary
Protocol
Database
13
JDBC Driver Types
• JDBC-ODBC Bridge, plus ODBC driver (Type 1)
– Simplest
– JDBC methods -> Translate JDBC methods to ODBC methods -> ODBC to native
methods -> Native methods API:
– First is JDBC-ODBC Bridge, which provides JDBC access via ODBC drivers.
Here the database client code must be loaded on each client machine which uses the
same driver. This kind of driver is most appropriate on a corporate network.
• Native-API, partly Java driver (Type 2)
– JDBC methods -> Map JDBC methods to native methods (calls to vendor library) ->
Native methods API (vendor library):
– Second is a native-API partly-java driver which converts JDBC calls into calls on
the client API for oracle, Sybase, Informix, DB2.. It requires the same binary code
to be loaded on each client machine.
14
JDBC-net, pure Java driver (Type 3)
JDBC methods -> Translate to Native API methods through TCP/IP network -> Native
API methods
Third types is a net-protocol all –Java driver that translates JDBC
calls into a DBMS independent net protocol which is subsequently,
translated to a DBMS protocol by a server. This net server
middleware is able to connect its Java clients to many different
databases.
Proprietary
Protocol
Database
16
Type 2: Native-API, Partly Java Driver
Database
17
Type 3: JDBC-Net, Pure Java Driver
• Translates JDBC calls into a database-
independent network protocol and sent to a Application Space
middleware server.
Java Application
• This server translates this DBMS-
independent protocol into a DBMS- Type 3 JDBC Driver
specific protocol and sent to the database
• Results sent back to the middleware and SQL Result
Command Set
routed to the client.
Middleware Space
JDBC Driver
Proprietary
Protocol
Database
18
Type 4: Native-Protocol, Pure Java Driver
• Pure Java drivers that communicate
directly with the vendor’s database Application Space
• JDBC commands converted to
database engine’s native protocol Java Application
directly
• Advantage: no additional translation
or middleware layer Type 4 JDBC Driver
• Improves performance.
SQL Command Result Set
Using Proprietary Using Proprietary
Protocol Protocol
Database
19
Essential JDBC Program
•J2EE components use a similar process for interacting with a
DBMS.
• This process is divided into Number of routines. These are….
• Import JDBC packages.
• Load and register the JDBC driver.
• Open a connection to the database.
• Create a statement object to perform a query.
• Execute the statement object and return a query resultset.
• Process the resultset.
• Close the resultset and statement objects.
• Close the connection. 20
Step 1. Import JDBC Packages
This is for making the JDBC API classes immediately available to the application
program. The following import statement should be included in the program irrespective
of the JDBC driver being used:
import java.sql.*;
This is for establishing a communication between the JDBC program and the
Oracle database. This is done by using the static registerDriver() method of
the DriverManager class of the JDBC API. The following line of code does this job:
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
21
Step 3. Connect to the DBMS
• Once the driver is loaded, the J2EE component must connect to the
DBMS using the DriverManager.getConnection() method.
• The java.sql.DriverManager class is the highest class in the java.sql
hierarchy and is responsible for managing driver information.
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest;
private Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db =
DriverManager.getConnection(url,userID,password);
}
22
• The DriverManager.getConnection() method is passed with the URL of the database,
the user ID and the password if required by DBMS.
• The URL is a string object that contains the driver name and the name of the database
that is being accessed by the J2EE component.
• The DriverManager.getConnection() method returns a Connection interface that is
used throughout the process to reference the database.
• The java.sql.Connection is another interface which manages the communication between
the driver and the J2EE component.
• The java.sql.Connection interface sends statements to the DBMS for processing.
23
Step 4 & 5. Create and Execute a SQL Statement
• Next is we have to send a SQL query to the DBMS for processing.
• A SQL query consists of a series of SQL commands that direct the
DBMS to do something such as to return a rows of data to the J2EE
component.
• Connection.createStatement() method is used to create a Statement object.
• The Statement object is then used to execute a query and return a
ResultSet object that contains the response from the DBMS.
• Once the ResultSet is received from the DBMS, the close() method
is called to terminate the statement.
24
Statement DataRequest;
private Connection Db;
ResultSet Results;
try
{
String query = " SELECT * FROM Customers";
DataRequest = Db.createStatement();
Results=DataRequest.executeQuery(query);
DataRequest.close();
}
25
Step 6. Process Data Returned by the DBMS
• The java.sql.ResultSet object is assigned the result received from
the DBMS after the query is processed.
• The java.sql.ResultSet object consists of methods used to interact
with data that is returned by the DBMS to the J2EE component.
ResultSet Results;
String FirstName, LastName, printrow;
boolean Records = Results.next();
if(!Records)
{ System.out.println("No data returned.");
return; }
else {
while(Results.next())
{ FirstName = Results.getString(FirstName);
LastName = Results.getString(LastName);
printrow = FirstName + " " + LastName;
System.out.println(printrow);
} } 26
Step 7. Terminate The Connection to the DBMS
• The connection to the DBMS is terminated by using the close()
method of the Connection object once the J2EE component is
finished accessing the DBMS.
• The close() method throws an exception if a problem is encountered
when disengaging the DBMS.
Db.close();
27
Example Program : Connecting to MS-Access
import java.sql.*;
import java.io.*;
public class DC
{
public static void main (String args[])
{
String url ="jdbc:odbc:access";
String user = " ";
String password = " ";
try
{
// load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
// create connection.
Connection c = DriverManager.getConnection(url) ;
// create statement
Statement s = c.createStatement( );
28
// execute statement and return resultset & stored in object
ResultSet r = s.executeQuery("SELECT ename, eid,
addr FROM emp") ;
// iterate the result set
while(r.next())
{
System. out.println (r.getString("ename") +"," +
r.getString ("eid") +" : "+ r.getString("addr")) ;
}
s.close( ) ;
}catch(Exception e)
{
System.out.println("Could not establish
connection") ;
}
}
}
29
Example Program : Connecting to MySql
import java.sql.*;
import java.io.*;
public class DCMysql
{
public static void main (String args[])
{
String url ="jdbc:mysql://localhost:3306/sample";
String user = "root";
String password = "hemanth";
try
{
// load the driver
Class.forName("com.mysql.jdbc.Driver") ;
// create connection.
Connection c =
DriverManager.getConnection(url,user,password) ;
30
// create statement
Statement s = c.createStatement( );
// execute statement and return resultset & stored in object
ResultSet r = s.executeQuery("SELECT ename, eid, addr
FROM emp") ;
// iterate the result set
while(r.next())
{
System. out.println (r.getString ("ename") +"," +
r.getString ("eid") +" : "+ r.getString("addr")) ;
}
s.close( ) ;
}catch(Exception e)
{
System.out.println("Could not establish
connection") ;
}
}
}
31
Statement Objects
• Once a connection to the database is opened, the J2EE component
creates and sends a query to access data contained in the database.
• One of the three types of Statement objects is used to execute the
query.
1. These objects are Statement, which executes a query immediately.
2. PreparedStatement, which is used to execute a compiled query.
3. CallableStatement, which is used to execute store procedures.
32
1. The Statement Object
The Statement object is used whenever J2EE component needs to immediately execute a
query without first having the query compiled.
• The Statement object contains the executeQuery() method, which passes the query as
an argument. The query is then transmitted to the DBMS for processing.
• The executeQuery() method returns one ResultSet object that contains rows, columns,
and metadata that represents data requested by query.
• The execute() method is used when there may be multiple results returned. It is a
boolean method which returns either true/false
• The executedUpdate() method returns an integer indicating the number of rows that
were updated by the query.
33
• The executeUpdate() is used to INSERT, UPDATE, DELETE, and
DDL statements.
A SQL query can be precompiled and executed by using the PreparedStatement object.
• Here a query is created as usual, but a question mark is used as a placeholder for a value
that is inserted into the query after the query is compiled.
• This statement gives you the flexibility of supplying arguments dynamically.
• The preparedStatement() method of Connection object is called to return the
PreparedStatement object.
• The preparedStatement() method is passed the query, which is then precompiled.
36
String url = "jdbc:odbc:CustomerInformation"; setString() is used to
String userID = "jim"; replace the question
String password = "keogh"; mark with the value
Statement DataRequest; passed.
ResultSet Results; Requires two parameters.
Connection Db; First an integer that
try identifies the position of
{ the question mark
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); placeholder.
Second is the value that
Db = DriverManager.getConnection(url,userID,password);
replaces the question
}catch(Exception e){} mark placeholder.
try
{
String query = “SELECT * FROM Customers WHERE CustNo = ? ”;
PreparedStatement pstatement = Db.prepareStatement(query);
pstatement.setString(1,”123”);
Results = pstatement.executeQuery();
// place code here to interact with the ResutlSet.
pstatement.close();
}
37
3. CallableStatement
If we use Interactive SQL to work with our database schema, instead of executing the
SQL statements one at a time, build up the set of commands in a dbisql command file.
Then we can execute this file in dbisql to build the database.
The definitions of the database objects form the database schema. we can think of
the schema as an empty database. The SQL statements for creating and modifying schemas
are called the data definition language (DDL).
Note: Only one user at a time can perform DDL statements on a table.
40
Interactive SQL Command File
41
JDBC In Action ResultSet
The ResultSet object contains methods that are used to copy data from the ResultSet into a
Java collection object or variable for further processsing.
• Data in a ResultSet is logically organized into a virtual table
consisting of rows and columns.
• The ResultSet uses a virtual cursor to point to a row of the virtual
table.
• The virtual cursor is positioned above the first row of data when the
ResultSet is returned by the executeQuery(). This means the virtual
cursor must be moved to the frist row using the next() method.
• The next() returns a boolean true if the row contains data; else false.
• Once the virtual cursor points to a row, the getxxx() is used to copy
data from the row to a collection, object or a variable.
42
Reading The ResultSet
ResultSet Results;
String FirstName, LastName, printrow;
boolean Records = Results.next();
if(!Records)
{
System.out.println("No data returned.");
return;
}
else
{
while(Results.next())
{
FirstName = Results.getString(1);
LastName = Results.getString(2);
printrow = FirstName + " " + LastName;
System.out.println(printrow);
}
}
43
Scrollable Resultset
In JDBC 2.1 API the virtual cursor can be moved backwards or positioned at a specific row.
• Six methods are there for Resultset object. They are first(), last(), previous(),
absolute(), relative() and getrow().
• first() method moves the virtual cursor to the first row in the Resultset.
• last() method positions the virtual cursor at the last row in the Resultset
• previous() method moves the virtual cursor to the previous row.
• absolute() method positions the virtual cursor to a specified row by the an integer value
passed to the method.
• relative() method moves the virtual cursor the specified number of rows contained in the
parameter.
44
• The parameter can be positive or negative integer.
• The getRow() method returns an integer that represents the number of the current row
in the Resultset.
• To handle the scrollable ResultSet , a constant value is passed to the Statement object
that is created using the createStatement().
Three constants.
- TYPE_FORWARD_ONLY
- TYPE_SCROLL_INSENSITIVE
- TYPE_SCROLL_SENSITIVE
• The other two allow the virtual cursor to move in both directions.
45
Updatable ResultSet
• Rows contained in the ResultSet can be updatable similar to how rows in a table can be
updated.
• This is possible by passing the createStatement() method of the Connection object the
CONCUR_UPDATABLE(read & update).
• CONCUR_READ_ONLY constant can be passed to the createStatement() method to
prevent the ResultSet from being updated.
• There are three ways in which a ResultSet can be changed.
• These are updating values in a row, deleting a row, and inserting a new row.
• All are accomplished by using the methods of the Statement object.
46
Update ResultSet
• Once the executeQuery() of the Statement object returns a ResultSet, the updatexxx() is
used to change the value of column in the current row of the ResultSet.
• The xxx in the updatexxx() is replaced with the data type of the column that is to be
updated.
• The updatexxx() requires two parameters. The first is either the number or name of
the column of the ResultSet that is being updated and the second is the value that will
replace the value in the column of the ResultSet.
47
Delete Row in the ResultSet
• The deleteRow() is used to remove a row from a ResultSet.
• The deleteRow() is passed an integer that contains the number of the row to be deleted.
• First use the absolute() method to move the virtual cursor to the row in the Resultset that
should be deleted.
• The value of that row should be examined by the program to assure it is the proper row
before the deleteRow() is called.
• The deleteRow() is then passed a zero integer indicating that the current row must be
deleted.
Resuts.deleteRow(0);
48
Insert Row in the ResultSet
• Inserting a row into the ResultSet is accomplished using basically the same technique as
is used to update the ResultSet.
• The updatexxx() is used to specify the column and value that will place into the column
of the ResultSet.
• The insertRow() is called after the updatexxx(), which causes a new row to be inserted
into the ResultSet.
49
Transaction Processing
• A transaction may involve several tasks.
• A database transaction consists of a set of SQL statements, each of which must be
successfully completed for the transaction to be completed.
• If any one fails, then the transaction must be rolled back.
• The database transaction is not completed until the J2EE component calls the commit()
method of the Connection object.
Commit and Rollback
– Commit – a call to commit() will commit everything that was done since the last commit
was issued
– Rollback – a call to rollback() will undo any changes since the last commit
50
JDBC - Batch Updates
Batch Processing allows we to group related SQL statements into a batch and
submit them with one call to the database.
When we send several SQL statements to the database at once, we reduce the
amount of communication overhead, thereby improving performance.
JDBC drivers are not required to support this feature. we should use
the DatabaseMetaData.supportsBatchUpdates() method to determine if the target
database supports batch update processing. The method returns true if your JDBC driver
supports this feature.
51
The addBatch() method of Statement, PreparedStatement, and
CallableStatement is used to add individual statements to the batch.
The executeBatch() is used to start the execution of all the statements grouped
together.
The executeBatch() returns an array of integers, and each element of the array
represents the update count for the respective update statement.
we can add statements to a batch for processing, we can remove them with
the clearBatch() method.
This method removes all the statements we added with the addBatch() method.
However, we cannot selectively choose which statement to remove.
52
Mapping Relational Data onto Java Objects
54
• BIT : a single bit value is represented by the JDBC type BIT that can be zero or one.
• TINYINT : an 8-bit integer value, between 0 and 255, can be signed or unsigned.
• SMALLINT : a 16-bit signed integer value between -32768 to 32767 is represented by
type SMALLINT.
• INTEGER : a 32-bit signed integer ranging between -2147483648 to 2147483647 is
represented by type INTEGER.
• BIGINT : a 64-bit signed integer value between – 9223372036854775808 to
9223372036854775807 is represented by type BIGINT.
• REAL : A single precision floating point number that supports seven digits of mantissa
is represented by the JDBC type REAL.
55
• DOUBLE : A double precision floating point number that supports15 digits of mantissa
is represented by the JDBC type REAL.
• FLOAT : it is basically equivalent to the JDBC type DOUBLE.
• DECIMAL and NUMERIC: both are similar, represent fixed- precision decimal values.
The precision and scale parameters are taken by these types. The precision is the total
number of decimal digits supported, and the scale is the number of decimal digit after
the decimal point.
• DATA, TIME and TIMESTAMP : these three relate to time.
• first type is knows as DATE type, represents a date consisting of day, month and year.
• second type is knows as TIME type, represents a time and which is consisting of hours,
minutes and seconds.
• third types is known as TIMESTAMP type that represents DATE plus TIME plus a
nanosecond field.
56
Advance JDBC Data Types
• BLOB data type : BINARY LARGE OBJECT represented by type
BLOB.
• CLOB : CHARACTER LARGE OBJECT represents type CLOB.
• ARRAY : represents type ARRAY.
57
SQL Type Java Type SQL Type Java Type
BLOB java.sql.Blob CHAR String
CLOB java.sql.Clob VARCHAR String
ARRAY java.sql.Array LONGVARCHAR String
STRUCT java.sql.Struct NUMERIC java.math.BigDecimal
REF java.sql.Ref DECIMAL java.math.BigDecimal
DATALINK java.sql.Types BIT Boolean
DATE java.sql.date TINYINT Byte
TIME java.sql.Time SMALLINT Short
TIMESTAMP java.sql.Timestamp INTEGER Integer
BIGINT Long
REAL float
FLOAT float
DOUBLE Double
BINARY Byte[]
VARBINARY Byte[]
LONGVARBINARY Byte[]
58
THE END
Dear Student,
Wishing you the very best for your upcoming exams! 📚✨
Stay confident, keep a positive mindset, and trust in all the hard work you've put into
your studies. Believe in yourself, stay focused, and give it your best effort.
May your dedication and perseverance lead you to great success! Good luck! 🍀
✍️Best wishes,
Mr. Santhosh SG
GOOD LUCK
59