The JDBC ResultSet interface provides methods for retrieving and manipulating the results of a database query. It represents a set of rows and provides access to the data stored in those rows. Here's an example code snippet that demonstrates the usage of the ResultSet interface:
import java.sql.*;
public class ResultSetExample {
public static void main(String[] args) {
// Connection parameters
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
try {
// Establishing a connection
Connection connection = DriverManager.getConnection(url, username, password);
// Creating a statement
Statement statement = connection.createStatement();
// Executing a query
String query = "SELECT * FROM employees";
ResultSet resultSet = statement.executeQuery(query);
// Iterating over the result set
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("--------------------");
}
// Closing resources
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In this example, we establish a connection to a MySQL database using the DriverManager.getConnection() method, passing in the URL, username, and password. We then create a Statement object using the connection's createStatement() method.
Next, we execute a query by calling the executeQuery() method on the Statement object. The query selects all the rows from the "employees" table. The result is returned as a ResultSet object.
We iterate over the result set using the next() method, which moves the cursor to the next row. Inside the loop, we retrieve the values from the current row using the appropriate getter methods, such as getInt() and getString(), based on the data type of each column. In this case, we assume that the "employees" table has columns named "id," "name," and "age."
We print the retrieved values and then continue to the next row until there are no more rows left.
Finally, we close the result set, statement, and connection using the close() method to release the resources and free up any database connections.
Note: The example assumes that you have the MySQL JDBC driver added to your project's classpath.