Java Database Connectivity with 5 Steps
1) Register the driver class
Syntax of forName() method
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in the classpath, and then JDBC driver manager can detect and load the driver automatically.
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
2) Create the connection object
Syntax of getConnection() method
Example to establish connection with the Oracle database
3) Create the Statement object
Syntax of createStatement() method
Example to create the statement object
4) Execute the query
Syntax of executeQuery() method
Example to execute query
5) Close the connection object
Syntax of close() method
Example to close connection
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement.
It avoids explicit connection closing step.