The Java ResultSetMetaData interface provides methods to obtain metadata about the structure and properties of a ResultSet object, which represents the result of a database query. It allows you to retrieve information such as the number of columns, column names, data types, and other properties of the result set. Here's an example code snippet demonstrating the usage of ResultSetMetaData:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class ResultSetMetaDataExample {
public static void main(String[] args) {
// Assuming you have a database named "mydatabase" and a table named "employees"
String jdbcUrl = "jdbc:mysql://localhost/mydatabase";
String username = "your-username";
String password = "your-password";
try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SELECT * FROM employees");
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
// Print column names
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);
System.out.print(columnName + "\t");
}
System.out.println();
// Print column types
for (int i = 1; i <= columnCount; i++) {
String columnType = metaData.getColumnTypeName(i);
System.out.print(columnType + "\t");
}
System.out.println();
// Print data
while (resultSet.next()) {
for (int i = 1; i <= columnCount; i++) {
Object value = resultSet.getObject(i);
System.out.print(value + "\t");
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In this example, we assume you have a MySQL database with a table named "employees." The code establishes a connection to the database using the JDBC driver, executes a SELECT query to fetch data from the "employees" table, and retrieves the ResultSet object. Then, we obtain the ResultSetMetaData object using resultSet.getMetaData().
With the ResultSetMetaData object, we can extract various information about the columns in the result set. In this example, we retrieve the column count using metaData.getColumnCount() and iterate through the columns to print their names and data types.
Finally, we iterate over the result set and retrieve and print the values of each column for each row.
Note that you'll need to replace "jdbc:mysql://localhost/mydatabase" with the appropriate JDBC URL for your specific database, and provide your database username and password.