在 ResultSet 中获取列名,可以使用以下方法:
String query = "SELECT * FROM tableName";
PreparedStatement preparedStatement = connection.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();
getMetaData()
方法获取 ResultSet 的元数据对象,该对象包含了关于结果集列的信息。ResultSetMetaData metaData = resultSet.getMetaData();
getColumnCount()
方法获取结果集的列数。int columnCount = metaData.getColumnCount();
getColumnName(int columnIndex)
方法获取每一列的名称。for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);
System.out.println("Column " + i + ": " + columnName);
}
将以上代码整合到一起:
String query = "SELECT * FROM tableName";
PreparedStatement preparedStatement = connection.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);
System.out.println("Column " + i + ": " + columnName);
}
运行此代码后,你将看到 ResultSet 中的所有列名。