Connection Interface in Java
A Connection object represents one session between your Java program and a database. Everything you do in JDBC goes through it: it creates statements, it controls transactions (commit and rollback), and it gives access to information about the database. A connection is a limited and fairly expensive resource: it holds a network socket and memory on the database server. So it must always be closed when you are finished. In this lesson, you will learn the methods of Connection, grouped by what they do, and what happens when a connection is closed.
Methods for Creating Statements
| Method | Description |
|---|---|
createStatement() | It is used to create a Statement for fixed SQL. |
prepareStatement(sql) | It creates a PreparedStatement for SQL with ? parameters. |
prepareCall(sql) | It creates a CallableStatement for stored procedures. |
createStatement(type, concurrency) | It creates a statement whose result sets can scroll or be updated. |
Methods for Transactions
| Method | Description |
|---|---|
setAutoCommit(boolean) | It turns auto-commit on or off. On (the default) means every statement is saved at once. |
commit() | It makes all changes since the last commit permanent. |
rollback() | It undoes all changes since the last commit. |
setSavepoint(), rollback(savepoint) | They mark a point in a transaction and undo back to it. |
setTransactionIsolation(level) | It sets how much concurrent transactions can see of each other. |
These are covered in "Transaction Management in JDBC".
Other Methods
| Method | Description |
|---|---|
close() | It releases the connection. |
isClosed() | It tells whether close() has been called. |
isValid(timeoutSeconds) | It checks that the connection still works, by contacting the database. |
getMetaData() | It returns a DatabaseMetaData describing the database. |
setReadOnly(boolean), isReadOnly() | They hint that only reads will happen. |
getCatalog(), getSchema() | They return the current database and schema names. |
Example: Inspecting and Closing a Connection
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Conn {
public static void main(String[] args) throws Exception {
Connection con = DriverManager.getConnection("jdbc:h2:mem:school");
System.out.println("autoCommit: " + con.getAutoCommit());
System.out.println("readOnly: " + con.isReadOnly());
System.out.println("valid: " + con.isValid(2));
System.out.println("catalog: " + con.getCatalog());
System.out.println("schema: " + con.getSchema());
System.out.println("isolation is READ_COMMITTED? "
+ (con.getTransactionIsolation()
== Connection.TRANSACTION_READ_COMMITTED));
try (Statement st = con.createStatement()) {
st.execute("CREATE TABLE note (text VARCHAR(20))");
}
con.close();
System.out.println("closed: " + con.isClosed());
System.out.println("valid: " + con.isValid(2));
try {
con.createStatement();
} catch (SQLException e) {
System.out.println("After close: " + e.getMessage());
}
}
}autoCommit: true
readOnly: false
valid: true
catalog: SCHOOL
schema: PUBLIC
isolation is READ_COMMITTED? true
closed: true
valid: false
After close: The object is already closed [90007-232]Explanation:
autoCommit: trueis the default for every new JDBC connection: each statement is its own transaction.isValid(2)asks the database to answer within 2 seconds. Connection pools use it to test a connection before handing it out.- The isolation level defaults to
READ_COMMITTEDin H2, as in PostgreSQL and Oracle. MySQL's default isREPEATABLE_READ. - After
close(),isClosed()istrue,isValidisfalse, and using the connection throwsSQLException. Closing a connection also closes the statements and result sets created from it.
Is a Connection Thread-Safe?
Treat a Connection as not safe to share between threads. A transaction belongs to the connection, so two threads using one connection would mix their work into the same transaction. The rule in practice: each thread, or each request, borrows its own connection from a pool and returns it when done.
isClosed vs isValid
| Method | What it tells you |
|---|---|
isClosed() | Only whether your code called close(). A connection whose network link has died still reports false. |
isValid(timeout) | Whether the connection really works now; it contacts the database. |
Common Mistakes
Not closing connections. The database has a limit on connections; leaks eventually cause "too many connections" errors.
Sharing one connection between threads. Transactions get mixed up.
Trusting isClosed() to detect a broken connection. Use isValid.
Leaving auto-commit off and forgetting to commit. The changes are lost when the connection closes.
Interview Corner
What is the Connection interface in JDBC?
java.sql.Connection represents a session with a specific database. It is the factory for Statement, PreparedStatement and CallableStatement, controls transactions through setAutoCommit, commit, rollback and savepoints, sets the transaction isolation level, and provides DatabaseMetaData through getMetaData(). By default a connection is in auto-commit mode. It must be closed to release database resources, and it should not be shared between threads.
Practice
- Easy: Print
con.getMetaData().getURL()andgetDatabaseProductVersion()for a connection. - Harder: Open a connection, call
setReadOnly(true), and try anINSERT. Record what your database does; the behavior is a hint and varies by driver.
Key Takeaways
Was this tutorial helpful?