Table of Contents

Java JDBC Connectivity steps

The following Five  steps are the basic steps involve in connecting a Java application with Database using JDBC.

1. Register the driver class:

Registering the driver class 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.

Example:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

2. Create Connection:

Create a connection using getConnection() method of DriverManager class. This method has several overloaded methods that can be used based on the requirement. It requires the database name, username, and password to establish the connection.

syntax:

getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)

Example:

Connection con = DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","password")

3. Create Statement:

Create statement object using createStatement() method. It is used to execute the SQL queries and defined in the Connection class.

syntax:

public Statement createStatement() throws SQLException

Example:

Statement s=con.createStatement();

4. Execute Query:

We can execute the query using executeQuery() method of the Statement interface. This method is used to execute SQL statements.

syntax:

public ResultSet executeQuery(String query) throws SQLException

Example:

ResultSet rs=statement.executeQuery("select * from emp");  

5. Close Connection:

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:

public void close() throws SQLException

Example:

con.close();

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?