The Connection interface is an important part of JDBC that helps a Java application communicate with a database. It represents an active connection where database operations are performed.
In this chapter, you will learn about the Connection interface, its role in JDBC, and how it is used to interact with databases.
A Connection is a session between a Java application and a database. It is used to establish a connection and perform operations on the database.
The Connection interface acts as a factory for Statement, PreparedStatement, and DatabaseMetaData objects. It also provides methods for transaction management such as commit(), rollback(), setAutoCommit(), and setTransactionIsolation().
To use the Connection interface in a program, we need to import it from the java.sql package.
Here is the syntax to important Connection interface:
Or, we can import all JDBC classes using:
The following table lists some commonly used methods of the Connection interface along with their descriptions:
| Method | Description |
|---|---|
| public Statement createStatement() | Creates a Statement object that is used to execute SQL queries. |
| public Statement createStatement(int resultSetType, int resultSetConcurrency) | Creates a Statement object with specified result set type and concurrency. |
| public void setAutoCommit(boolean status) | Sets the commit mode. By default, it is true (auto-commit enabled). |
| public void commit() | Saves all changes made since the last commit or rollback permanently. |
| public void rollback() | Cancels all changes made since the last commit or rollback. |
| public void close() | Closes the connection and releases JDBC resources immediately. |
There are some common Connection interface constant fields that are present in the Connect interface. These fields specify the isolation level of a transaction:
The following example demonstrates how to use the Connection interface to connect to a database and perform a simple query.
Output:
1 Rahul 2 Priya 3 Amit
Explanation:
This example shows how a program connects to a database using the Connection interface, executes a query, and displays the result. The connection is created using DriverManager, and data is fetched using a Statement and ResultSet.
We request you to subscribe our newsletter for upcoming updates.