5 Steps to connect to the database in java

There are 5 steps to connect any java application with the database in java using JDBC. They are as follows:

  1. Register the driver class
  2. Creating connection
  3. Creating statement
  4. Executing queries
  5. Closing connection

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.

Syntax of forName() method

Flash Soon


Example to register the OracleDriver class

Flash Soon


2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method

Flash Soon


Example to establish connection with the Oracle database

Flash Soon


3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database.

Syntax of createStatement() method

Flash Soon


Example to create the statement object

Flash Soon


4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

Flash Soon


Example to execute query

Flash Soon


5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.

Syntax of close() method

Flash Soon


Example to close connection

Flash Soon



Advertisement

© Sapster 2017