Java Exercise
In this exercise, you will create a Java program that connects to a database using JDBC. The program will execute SQL queries to retrieve information and then display the results. You will begin by establishing a connection to the database, execute a SELECT query, and process the returned data. This exercise will help you understand how to integrate databases into Java applications, using SQL queries to interact with data effectively.
Instructions:
- Configure your environment to work with JDBC and ensure you have an accessible database.
- Create a connection to the database using the appropriate JDBC driver for your database.
- Execute an SQL query using a SELECT statement to retrieve data.
- Receive and process the results using a
ResultSet
.
- Close the connection once you have finished processing the data.
This exercise will give you a solid understanding of how to interact with databases from Java, using JDBC to execute SQL queries and process the results efficiently.
View Example Code
import java.sql.*;
public class SQLQuery {
public static void main(String[] args) {
// Define variables for the connection
String url = "jdbc:mysql://localhost:3306/my_database"; // Database URL
String username = "root"; // Database username
String password = "my_password"; // Database password
// Connect to the database and execute the query
try (Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement()) {
// Execute a SQL query
String sql = "SELECT id, name FROM employees";
ResultSet rs = stmt.executeQuery(sql);
// Process the query results
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// Close ResultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:
ID: 1, Name: Juan Pérez
ID: 2, Name: Ana Gómez
ID: 3, Name: Carlos Ruiz
This program demonstrates how to execute a SQL query in Java using JDBC. The program establishes a connection to a MySQL database, executes a SELECT query to retrieve data from the employees
table, and then processes the results to print the values for the id
and name
columns for each record. The output shows the data retrieved from the database, allowing you to verify that the query executed correctly.