0% found this document useful (0 votes)
2 views

Steps to Connect Java Application with Database

The document outlines the steps to connect a Java application to a database, including importing packages, loading and registering drivers, establishing a connection, creating a statement, executing a query, and closing connections. It provides a code example that connects to a MySQL database and retrieves employee data. The example demonstrates how to handle SQL exceptions and print the results from the database query.

Uploaded by

Balaji Sri Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Steps to Connect Java Application with Database

The document outlines the steps to connect a Java application to a database, including importing packages, loading and registering drivers, establishing a connection, creating a statement, executing a query, and closing connections. It provides a code example that connects to a MySQL database and retrieves employee data. The example demonstrates how to handle SQL exceptions and print the results from the database query.

Uploaded by

Balaji Sri Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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.*;

public class SelectExample {

static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";

static final String USER = "guest";

static final String PASS = "guest123";

static final String QUERY = "SELECT id, first, last, age FROM Employees";

public static void main(String[] args) {

// Open a connection

try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(QUERY);) {

// Extract data from result set

while (rs.next()) {

// Retrieve by column name

System.out.print("ID: " + rs.getInt("id"));

System.out.print(", Age: " + rs.getInt("age"));

System.out.print(", First: " + rs.getString("first"));

System.out.println(", Last: " + rs.getString("last"));

} 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:\>

You might also like