Java 如何检查 ResultSet 是否包含特定命名的字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3942583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:19:19  来源:igfitidea点击:

How to check that a ResultSet contains a specifically named field?

javajdbcresultset

提问by Ivan

Having rs, an instance of java.sql.ResultSet, how to check that it contains a column named "theColumn"?

有了rsjava.sql.ResultSet 的一个实例,如何检查它是否包含名为“theColumn”的列?

采纳答案by Buhake Sindi

You can use ResultSetMetaDatato iterate through the ResultSet columns and see if the column name matches your specified column name.

您可以使用ResultSetMetaData遍历 ResultSet 列并查看列名是否与您指定的列名匹配。

Example:

例子:

ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();

// get the column names; column indexes start from 1
for (int i = 1; i < numberOfColumns + 1; i++) {
    String columnName = rsMetaData.getColumnName(i);
    // Get the name of the column's table name
    if ("theColumn".equals(columnName)) {
        System.out.println("Bingo!");
    }
}

回答by Boris Pavlovi?

Try using the method ResultSet#findColumn(String)

尝试使用方法ResultSet#findColumn(String)

private boolean isThere(ResultSet rs, String column)
{
  try
  {
    rs.findColumn(column);
    return true;
  } catch (SQLException sqlex)
  {
    logger.debug("column doesn't exist {}", column);
  }
  return false;
}

回答by Alois Cochard

You can do:

你可以做:

rs.findColumn("theColum")

and check for SQLException

并检查 SQLException

回答by darri

Use the ResultSetMetaDataobject provided by the ResultSetobject via rs.getMetaData()

使用对象提供的ResultSetMetaDataResultSet对象通过rs.getMetaData()

回答by madx

Use the ResultSetMetaDataclass.

使用ResultSetMetaData类。

public static boolean hasColumn(ResultSet rs, String columnName) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    for (int x = 1; x <= columns; x++) {
        if (columnName.equals(rsmd.getColumnName(x))) {
            return true;
        }
    }
    return false;
}