In the post Java JDBC Steps to Connect to DB we have already seen a complete example using the interfaces Driver, Connection, Statement and ResultSet provided by the JDBC API.
In this post we’ll see Connection interface in detail.
Connection interface
Connection interface resides in java.sqlpackage and it represents a session with a specific database you are connecting to. SQL statements that you want to execute, results that are returned all that happens with in the context of a connection.
You can get a Connection object by using the getConnection() method of the DriverManagerclass.
Using Connection class object -
- You can get the object of Statement
- You can get the information about the database it is connecting to
- Connection also provides method for transaction management
Fields in the Connection interface
Connection interface provides a set of fields for specifying transaction isolation level -
- TRANSACTION_NONE - A constant indicating that transactions are not supported.
- TRANSACTION_READ_COMMITTED - A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.
- TRANSACTION_READ_UNCOMMITTED - A constant indicating that dirty reads, non-repeatable reads and phantom reads can occur.
- TRANSACTION_REPEATABLE_READ - A constant indicating that dirty reads and non-repeatable reads are prevented; phantom reads can occur.
- TRANSACTION_SERIALIZABLE - A constant indicating that dirty reads, non-repeatable reads and phantom reads are prevented.
Frequently used methods of the Connection
Some of the frequently used methods of the Connection are as follows -
For creating statement
- createStatement() - Creates a Statement object for sending SQL statements to the database.
- prepareStatement(String sql) - Creates a PreparedStatement object for sending parameterized SQL statements to the database.
- prepareCall(String sql) - Creates a CallableStatement object for calling database stored procedures.
For getting information about the DB
- getMetaData() - Returns a DatabaseMetaData object containing metadata about the connected database.
For transaction management
- setAutoCommit(boolean autoCommit) - Sets this connection's commit mode to true or false.
- setTransactionIsolation(int level) - Attempts to changes the transaction isolation level for this Connection object to the one given.
- rollback() - Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.
- commit() - Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.
Reference : https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html
That's all for this topic Connection Interface in Java-JDBC. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -