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.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLQueries {
private static final String URL = "jdbc:mysql://localhost:3306/myDatabase";
private static final String USER = "user";
private static final String PASSWORD = "password";
public static void main(String[] args) {
try (
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT name, salary FROM employees")
) {
while (rs.next()) {
String name = rs.getString("name");
double salary = rs.getDouble("salary");
System.out.println("Employee: " + name + ", Salary: " + salary);
}
} catch (SQLException e) {
System.err.println("SQL Error: " + e.getMessage());
}
}
}
Output:
Employee: Juan, Salary: 5000.0
Employee: Ana, Salary: 4500.0
Employee: Carlos, Salary: 6000.0
This program demonstrates how to handle database connections and perform transactions using JDBC in Java. A connection to the database is established, several SQL operations are performed within a transaction, and if everything is successful, the transaction is committed. If an error occurs, transactions are rolled back using the rollback()
method, and resources (connections) are gracefully closed at the end.