Java Database Connectivity
Java Database Connectivity
independent interface which helps to connect java programs with various databases such as
Oracle, My SQL, MS Access and SQL Server. It provides ways to query and update the database
using Structured Query Language (SQL) update statements such as CREATE, DELETE,
INSERT and UPDATE and query statements like SELECT. It is almost similar to ODBC (Open
Database Connectivity) that was provided by Microsoft.
To connect the java program or application with the database there are five steps to be followed:
1. Load the Driver: Driver helps to make a connection to the database hence driver must be
loaded once in the program. Class.forName(): By using this, the driver’s class file is
loaded in the memory during run time. There is no need to create a new object. For
example:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2. Creating Connections: After the driver is loaded, the connection is set up. The connection
object uses username, password, and URL to set up the connection. URL has a
predefined format which contains database name, the driver used, IP address where the
database is stored, Port number and the service provider. The connection can be set up by
using the command:
3. Creating Statement: After establishing the connection, the user can interact with the
database. The interfaces such as JDBC statement, PreparedStatement, CallableStatement
provides methods that allow a user to send SQL statements and get data from the
database. Command used to create statement is-
4. Executing Query: The SQL query is executed to interact with the database. A query can
be for updating/inserting in the database or for retrieving data. Statement interface
provides two methods i.e. executeQuery() method to execute queries for retrieving data
while executeUpdate() method to execute queries for updating or inserting. For Example:
stmt.executeUpdate(“DELETE TABLENAME”);
5. Closing Connection: After executing our query, the data user wanted to update or retrieve
has been done so now it’s time to close the established connection. The connection
interface provides a method close() to close the connection. For example:
con.close();
Components of JDBC Architecture
The components are explained below.
Driver Manager: It is a class that contains a list of all drivers. When a connection
request is received, it matches the request with the appropriate database driver using a
protocol called communication sub-protocol. The driver that matches is used to establish
a connection.
Driver: It is an interface which controls the communication with the database server.
Statement: This interface creates an object to submit SQL queries or statements to the
database.
ResultSet: This contains the results retrieved after the execution of the SQL statements
or queries.
SQLException: Any errors that occur in database application are handled by this class.
Basic JDBC architectural diagram