Steps to connect a Java Application to Database
The following 5 steps are the basic steps involve in connecting a Java application with Database using JDBC.
- Register the Driver
- Create a Connection
- Create SQL Statement
- Execute SQL Statement
- Closing the connection
Register the Driver
It is first an essential part to create JDBC connection. JDBC API provides a method Class.forName()
which is used to load the driver class explicitly. For example, if we want to load a jdbc-odbc driver then the we call it like following.
Example to register with JDBC-ODBC Driver
Create a Connection
After registering and loading the driver in step1, now we will create a connection using getConnection()
method of DriverManager class. This method has several overloaded methods that can be used based on the requirement. Basically it require the database name, username and password to establish connection. Syntax of this method is given below.
Syntax
This is a sample example to establish connection with Oracle Driver
Create SQL Statement
In this step we will create statement object using createStatement() method. It is used to execute the sql queries and defined in Connection class. Syntax of the method is given below.
Syntax
Example to create a SQL statement
Execute SQL Statement
After creating statement, now execute using executeQuery()
method of Statement interface. This method is used to execute SQL statements. Syntax of the method is given below.
Syntax
Example to execute a SQL statement
In this example, we are executing a sql query to select all the records from the user table and stored into resultset that further is used to display the records.
Closing the connection
This is final step which includes closing all the connection that we opened in our previous steps. After executing SQL statement you need to close the connection and release the session. The close()
method of Connection interface is used to close the connection.
Syntax
Example of closing a connection
Now lets combine all these steps into a single example and create a complete example of JDBC connectivity.
Example: All Steps into one place
Â