Steps to connect database in java using JDBC are given below:
- Load the JDBC driver.
- Connection.
- Statement.
- 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.
Syntax:
Class.forName("driverClassName");
To load or register OracleDriver class:
Syntax:
Class.forName("oracle.jdbc.driver.OracleDriver");
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.
Syntax:
Connection connection = DriverManager.getConnection(url, user, password)
To create a connection with Oracle database:
Syntax:
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.
Syntax:
Statement stmt=conn.createStatement();
4. Execute statement:
Statement interface provides the methods to execute a statement.
To execute a statement for select query use below:
Syntax:
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.
Syntax:
connection.close();
Next Topic: Connect to Oracle database with JDBC driver.
Previous Topic: JDBC driver.