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



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.