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

后端 未结 5 1030
广开言路
广开言路 2020-12-29 22:04

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

相关标签:
5条回答
  • 2020-12-29 22:45

    You can do:

    rs.findColumn("theColum")
    

    and check for SQLException

    0 讨论(0)
  • 2020-12-29 22:46

    Use the ResultSetMetaData class.

    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;
    }
    
    0 讨论(0)
  • 2020-12-29 22:56

    Use the ResultSetMetaData object provided by the ResultSet object via rs.getMetaData()

    0 讨论(0)
  • 2020-12-29 23:04

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

    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!");
        }
    }
    
    0 讨论(0)
  • 2020-12-29 23:11

    Try using the method 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;
    }
    
    0 讨论(0)
提交回复
热议问题