9.B] Describe various steps of JDBC with code snippets.
Answer:-
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:
- Register the driver class
- Creating connection
- Creating statement
- Executing queries
- Closing connection
1. Register the Driver Class
- Purpose: Load the JDBC driver to connect to the database.
- Method:
Class.forName("driverClassName")
Class.forName("com.mysql.cj.jdbc.Driver"); // Example for MySQL2. Create the Connection Object
- Purpose: Establish a connection to the database.
- Method:
DriverManager.getConnection(url, user, password)
String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "username"; String password = "password"; Connection con = DriverManager.getConnection(url, user, password);
3. Create & Execute Query
- Purpose: Create a statement and execute SQL queries.
- Methods:
createStatement()andexecuteQuery()
Statement st = con.createStatement(); String sql = "SELECT id, name FROM users"; ResultSet rs = st.executeQuery(sql);
4. Process Data Returned from DBMS
- Purpose: Iterate through the
ResultSetto process the retrieved data. - Method:
rs.next()
while (rs.next()) {
int id = rs.getInt(1); // Retrieve the first column
String name = rs.getString(2); // Retrieve the second column
System.out.println(id + " " + name);
}5. Close the Connection Object
- Purpose: Close the
ResultSet,Statement, andConnectionto release resources. - Methods:
rs.close(),st.close(),con.close()
rs.close(); st.close(); con.close();
Summary
- Register the Driver:
Class.forName("com.mysql.cj.jdbc.Driver");- Create Connection:
Connection con = DriverManager.getConnection(url, user, password);
- Create and Execute Query:
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT id, name FROM users");- Process Data:
while (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println(id + " " + name);
}- Close Resources:
rs.close(); st.close(); con.close();
This process covers the essential steps to connect to a database, execute queries, and handle the results in a Java application using JDBC.
