Steps to connect database in java using JDBC are given below:
- Load the JDBC driver.
- Execute statement.
- Close database connection.
1. Load the JDBC driver:
First step is to load or register the JDBC driver for the database. Class class provides forName() method to dynamically load the driver class.
To load or register OracleDriver class:
2. Create connection:
Second step is to open a database connection. DriverManager class provides the facility to create a connection between a database and the appropriate driver.To open a database connection we can call getConnection() method of DriverManager class.
Connection connection = DriverManager.getConnection(url, user, password)
To create a connection with Oracle database:
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","user","password");
3. Create statement:
The statement object is used to execute the query against the database. Connection interface acts as a factory for statement object. A statement object can be any one of the Statement, CallableStatement, and PreparedStatement types .To create a statement object we have to call createStatement() method of Connection interface. Connection interface also provides the transaction management methods like commit() and rollback() etc.
4. Execute statement:
Statement interface provides the methods to execute a statement.
To execute a statement for select query use below:
ResultSet resultSet = stmt.executeQuery(selectQuery);
5. Close database connection:
After done with the database connection we have to close it. Use close() method of Connection interface to close database connection. The statement and ResultSet objects will be closed automatically when we close the connection object.
Next Topic: Connect to Oracle database with JDBC driver.
Previous Topic: JDBC driver.