JDBC Connection Interface
The Connection interface provided by java.sql allows a Java application to maintain an individual session with a particular database. JDBC utilizes the Connection interface to establish communication between Java applications and relational databases.
Key Responsibilities
- Establishes a session with the database
- Creates Statement, PreparedStatement, and CallableStatement
- Manages transactions (commit, rollback, auto-commit)
- Provides metadata about the database
How to Obtain a Connection
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "password");
Method
| Method | Description |
|---|---|
| createStatement() | Creates a Statement object |
| prepareStatement(String sql) | Creates a PreparedStatement object |
| setAutoCommit(boolean flag) | Enables/disables automatic transaction commit |
| commit() | Commits current transaction |
| rollback() | Rolls back current transaction |
| close() | Closes the connection |
| isClosed() | Checks if connection is closed |
| getMetaData() | Retrieves metadata about the database |
Example
import java.sql.*;
public class ConnectionExample {
public static void main(String[] args) {
try {
// Load driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);
// Create a statement and execute a query
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
while (rs.next()) {
System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
}
// Close the connection
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Best Practices
- Use try-with-resources to automatically close the Connection
- Always close connections after use
- Use connection pooling for production
- Disable auto-commit during complex operations
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com