Working with Result Sets
When retrieving data from a database using JDBC, the data is typically returned as a result set. A result set is a table-like structure that contains the rows and columns of the data fetched from the database.
To work with result sets in JDBC, you need to perform the following steps:
- Execute a statement or a prepared statement that queries the database.
- Obtain the result set object by calling the
executeQuery
method. - Iterate over the result set using a loop and process the data in each row.
- Close the result set object after you're done.
Here's an example of retrieving data from a result set in JDBC:
TEXT/X-JAVA
1import java.sql.Connection;
2import java.sql.DriverManager;
3import java.sql.PreparedStatement;
4import java.sql.ResultSet;
5
6public class Main {
7 public static void main(String[] args) {
8 // Replace with your database URL, username, and password
9 String url = "jdbc:mysql://localhost:3306/mydatabase";
10 String username = "root";
11 String password = "password";
12
13 try {
14 // Establish a connection to the database
15 Connection connection = DriverManager.getConnection(url, username, password);
16
17 // Create a statement
18 String query = "SELECT * FROM employees";
19 PreparedStatement statement = connection.prepareStatement(query);
20
21 // Execute the query
22 ResultSet resultSet = statement.executeQuery();
23
24 // Process the result set
25 while (resultSet.next()) {
26 int id = resultSet.getInt("id");
27 String name = resultSet.getString("name");
28 int age = resultSet.getInt("age");
29
30 System.out.println("Employee ID: " + id);
31 System.out.println("Employee Name: " + name);
32 System.out.println("Employee Age: " + age);
33 System.out.println();
34 }
35
36 // Close the result set
37 resultSet.close();
38
39 // Close the statement
40 statement.close();
41
42 // Close the connection
43 connection.close();
44 } catch (Exception e) {
45 // Handle the exception
46 System.out.println("Error executing query: " + e.getMessage());
47 }
48 }
49}
xxxxxxxxxx
49
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Main {
public static void main(String[] args) {
// Replace with your database URL, username, and password
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
try {
// Establish a connection to the database
Connection connection = DriverManager.getConnection(url, username, password);
// Create a statement
String query = "SELECT * FROM employees";
PreparedStatement statement = connection.prepareStatement(query);
// Execute the query
ResultSet resultSet = statement.executeQuery();
// Process the result set
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment