Explain the need of JDBC? Explain steps involved in connecting a databases using JDBC.

QuestionsExplain the need of JDBC? Explain steps involved in connecting a databases using JDBC.
manish.mishraPublished on: 6/21/2021 1:49:07 PM



1 Answers
Answer is under review.

Steps:

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.

Class.forName("oracle.jdbc.driver.OracleDriver");

Create the connection object

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

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

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.

Statementstmt=con.createStatement();

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.

ResultSetrs=stmt.executeQuery("select*fromemp");

while(rs.next())

{

System.out.println(rs.getInt(1) "" rs.getString(2));

}

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.

con.close();