如何确定ResultSet中是否存在列名? [英] How can I determine if the column name exist in the ResultSet?

查看:431
本文介绍了如何确定ResultSet中是否存在列名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于ResultSet包含从动态SQL返回的数据,是否有任何方法可以确定ResultSet是否包含特定的列名?例如,如果我运行 rs.getString(Column_ABC); 但是Column_ABC实际上不存在,它将抛出异常。如何测试ResultSet是否可以从名为Column_ABC的列中获取数据?

As the ResultSet contains the data returned from the dynamic SQL, if there are any method to determine if the ResultSet contains a particular column name ? For example , if I run rs.getString("Column_ABC"); but Column_ABC does not really exist, it will throw out the exception . How can I test if the ResultSet can get a data from a column named "Column_ABC" ?

推荐答案

使用 ResultSetMetaData 类。

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;
}

我不明白的是为什么需要这个功能。正在执行的查询或存储过程应具有已知结果。应该知道查询的列。需要这样的功能可能表明某处存在设计问题。

The thing I don't understand is why this function would ever be needed. The query or stored procedure being executed should have known results. The columns of the query should be known. Needing a function like this may be a sign that there is a design problem somewhere.

这篇关于如何确定ResultSet中是否存在列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆