如何确定ResultSet中是否存在列名?

时间:2010-08-30 11:21:51

标签: java jdbc resultset

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

6 个答案:

答案 0 :(得分:86)

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

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

答案 1 :(得分:8)

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

答案 2 :(得分:7)

不确定这是否比Erick的答案更有效或更低效,但它更容易。

String str;

try {
    str = rs.getString(columnName);
} catch (java.sql.SQLException e) {
    str = null;
}

答案 3 :(得分:-1)

 private void getRecentlyTag(final OnResponseListener listener){

  new Thread(){
@Override
public void run() {
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(Constants.API_URL);
        urlConnection = (HttpURLConnection) url
                .openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoInput(true);
        urlConnection.connect();
        String response = Tools.streamToString(urlConnection
                .getInputStream());
        JSONObject jsonObj = (JSONObject) new JSONTokener(response)
                .nextValue();
        if(listener!=null){
          listener.onResponseReceived(jsonObj);
        }

    }catch(Exception exc){
        exc.printStackTrace();
    }finally {
        if(urlConnection!=null){
            try{
                urlConnection.disconnect();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
  //  mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
} }

interface OnResponseListener{
 void onResponseReceived(JSONObject obj);
}

在java版本&gt; = 7中,您可以选择在Re​​sultSet中传递类型#getObject方法

答案 4 :(得分:-1)

resultSet.getColumnMetaData()。contains(columnName)

答案 5 :(得分:-14)

如果不是rs.getString(“Column_ABC”)=则没有 '你的代码在这里