Skip to content

Connection interface

Atul Dwivedi edited this page Jan 18, 2017 · 4 revisions
  • A Connection object represents a connection with specific database and acts as session for database operations
    Connection con = DriverManager.getConnection(..);

  • All SQL statement execution and results are returned within the context of connection

  • The Connection interface is a factory of Statement, PreparedStatement and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement, PreparedStatement and DatabaseMetaData.

    Stetement stmt = con.createStatement();
    PreparedStatement stmt = con.prepareStatement(sqlQuery);
    DatabaseMetaData dbmd = con.getMetaData();

    Where con represents Connection object.

  • The Connection interface provide many methods for transaction management like commit(), rollback() etc

Commonly used methods of Connection interface

Modifier and Type Method and Description
Statement createStatement()
Creates a Statement object for sending SQL statements to the database.
Statement createStatement(int resultSetType, int resultSetConcurrency)
Creates a Statement object that will generate ResultSet objects with the given type and concurrency.
Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
Creates a Statement object that will generate ResultSet objects with the given type, concurrency, and holdability.
PreparedStatement prepareStatement(String sql)
Creates a PreparedStatement object for sending parameterized SQL statements to the database.
CallableStatement prepareCall(String sql)
Creates a CallableStatement object for calling database stored procedures.
void setAutoCommit(boolean autoCommit)
Sets this connection's auto-commit mode to the given state.
void commit()
Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.
void rollback()
Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.
void close()
Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.