简体   繁体   中英

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

I have a result set 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? 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.

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)+" ");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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