Steps to Connect Java Application with Database
Steps to Connect Java Application with Database
Below are the steps that explains how to connect to Database in Java:
Step 1 – Import the Packages
Step 2 – Load the drivers using the forName() method
Step 3 – Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5 – Create a statement
Step 6 – Execute the query
Step 7 – Close the connections
import java.sql.*;
static final String QUERY = "SELECT id, first, last, age FROM Employees";
// Open a connection
ResultSet rs = stmt.executeQuery(QUERY);) {
while (rs.next()) {
} catch (SQLException e) {
e.printStackTrace();
}
C:\>java SelectExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatima
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>