简体   繁体   English

用列名打印所有查询结果的最有效方法是什么?

[英]What is the most efficient way to print all query results with column names?

I have a result set ResultSet rs=stmt.executeQuery(); 我有一个结果集ResultSet rs=stmt.executeQuery(); I wrote a method to print query results as following 我编写了一种打印查询结果的方法,如下所示

public void printResults(ResultSet rs) {
    // Getting column names
    int j = 1;
    while (true) {
        try {
    System.out.print(rs.getMetaData().getColumnName(j)+"    ");
    j++;
        }
        catch (Exception e) {
            System.out.println("\n");
            break;
        }
    }

    // Getting results
    while(rs.next()) {
        int i = 1;
        while (true) {
            try {
        System.out.print(rs.getString(i)+"  ");
        i++;
            }
            catch (Exception e) {
                System.out.println("\n");
                break;
            }
        }
    }
}

My issue is : is it a good idea to use try && catch ... I feel that it is not? 我的问题是:使用try && catch ...是个好主意吗?我觉得不是吗? Does it impact speed? 它会影响速度吗? What is a better way? 有什么更好的方法?

Thank You

You can get column number by 您可以通过获取列号

 ResultSetMetaData meta= rs.getMetaData();
 int columnNum=meta.getColumnCount();

Loop with this columnNum to get the result as well as column name. 循环使用此columnNum以获取结果以及列名。

for(int i=1;i<=columnNum;i++){
    System.out.print(meta.getColumnName(i)+" ");
}

//Get the data
while(rs.next){
  for(int i=1;i<=columnNum;i++){
    System.out.print(rs.getString(i)+" ");
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM