Skip to main content

Executing SQL queries

After setting up the connection with the database, the next step is to execute query on the database.

Code Execution: Retrieving Data with JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCTutorial {
public static void main(String[] args) {
// Assuming connection setup code is already present
Connection connection = /* Your existing connection code here */;

try {
// Define the SQL query
String query = "SELECT * FROM employees";

// Create a PreparedStatement for the query
PreparedStatement preparedStatement = connection.prepareStatement(query);

// Execute the query and store the results in a ResultSet
ResultSet resultSet = preparedStatement.executeQuery();

// Process the result set
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double salary = resultSet.getDouble("salary");
System.out.println("ID: " + id + ", Name: " + name + ", Salary: " + salary);
}

// Close resources
preparedStatement.close();
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}

// Assuming your existing code to close the connection
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Explanation of Code Components:

  • SQL Query Definition: The query "SELECT * FROM employees" is defined to retrieve all rows from the "employees" table.

  • PreparedStatement Execution: The PreparedStatement is employed to execute the SQL query. This approach enhances security and performance.

  • Result Processing: The ResultSet handles the results of the query. We iterate through the result set, extracting data for each row, and print it to the console.

  • Resource Closure: It's essential to close resources, including the PreparedStatement, ResultSet, and the database Connection. This practice ensures the proper release of resources and prevents memory leaks.

Output:

Assuming there is data in the "employees" table, running this program will display the retrieved information:

ID: 1, Name: John Doe, Salary: 50000.0
ID: 2, Name: Jane Smith, Salary: 60000.0