在 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 中的所有列名。