Java applications that use a database connection and the JDBC API have a distinct life cycle.
The figure shows the six stages in the life cycle of a JDBC application:
The list below explains each step of the life cycle.
Steps of the JDBC Life Cycle
-
The first step in a JDBC application is to load the JDBC driver and initialize it. The JDBC driver is loaded by calling the
Class.forName().newInstance()method. The JDBC driver is assumed to be in the CLASSPATH. -
After loading the JDBC driver, the JDBC application uses the JDBC API to communicate with the database. To do this, the application needs to open a connection to the database using the
connect()method of theDriverclass. A database connection can be opened only by authenticating with the database. The authentication information can be passed in two different ways: as separate parameters to theconnect()method or in theparameter of the connect()method. This depends on the JDBC driver implementation. The database connection can be stored in the Java class and reused at any point to interact with the database as long as the connection is alive. -
After obtaining a database connection, the JDBC application can use the
Statement,PreparedStatement, orCallableStatementobjects to execute SQL statements. ThePreparedStatementandCallableStatementare unique purpose statement interfaces inherited from theStatementinterface. The JDBC driver implements these interfaces to provide the underlying functions. The database connection can create theStatement,PreparedStatement, andCallableStatement. Any number of Statement,PreparedStatement, andCallableStatementobjects can be created from a live database connection. -
After creating a
Statement,PreparedStatement, orCallableStatement, SQL statements such as inserts, updates, and queries can be executed using the relevant methods provided in theStatement,PreparedStatement, andCallableStatementinterfaces. -
If an SQL statement query is executed, the
ResultSetandResultSetMetaDatainterfaces can be used by the JDBC application to retrieve the data from the database. -
The final stage in the JDBC application is the closing of the database connection. Closing the database connection using the "close()" method of the Connection object frees up expensive resources on the database.
Summary: What is the JDBC Connection
- Many Java applications use a database connection and JDBC API
- These applications have a six-stage connection process
- The JDBC lifecycle involves establishing a connection to a database, creating and executing SQL statements, processing results, and finally, closing the connection to release resources.
JDBC Life Cycle
- Load the JDBC driver
- Open a database connection
- Create a
Statement/PreparedStatement/CallableStatement - Execute SQL statements
- Retrieve and potentially process the results of any SQL query
- Close database connection