![]() |
VOOZH | about |
The Connection interface in Java JDBC represents a session between a Java application and a database. It is used to establish communication, execute SQL queries, and manage transactions. It acts as a bridge that enables interaction with the database.
The architecture flow shows how a Java application sends a query through the JDBC driver (acting as a translator) to the database, and the processed result is returned back as a ResultSet.
This diagram illustrates how a Java application interacts with a database using JDBC components:
A Connection object is created using the DriverManager class:
Connection con = DriverManager.getConnection(url, username, password);
1. createStatement(): Creates a Statement object to execute SQL queries.
Statement stmt = con.createStatement();
2. prepareStatement(String sql): Creates a PreparedStatement for parameterized queries.
PreparedStatement ps = con.prepareStatement("SELECT * FROM student WHERE id = ?");
3. prepareCall(String sql): Creates a CallableStatement for stored procedures.
CallableStatement cs = con.prepareCall("{call procedure_name()}");
4. setAutoCommit(boolean status): Controls auto-commit mode.
con.setAutoCommit(false);
5. commit(): Saves the transaction permanently.
con.commit();
6. rollback(): Reverts changes in case of failure.
con.rollback();
7. close(): Closes the database connection.
con.close();
Example Code: