简体   繁体   中英

Preview sql result columns in java

Is there any way for 'previewing' sql select statements? What I'm trying to do is to get the names of the columns that are returned by a sql statement without actually running the statement?

On application startup i need to know the column names, the problem is that some of the queries can run for awhile.

ResultSetMetaData may help

You still have to execute the query to get the meta data, but you may be able to alter add a restriction to the where clause which means it returns zero rows very quickly. For example you could append and 1 = 0 to the where clause.

The DBMS still has to do all the query parsing that it would normally do - it just means that the execution should hopefully fail very quickly

You didn't mention your DBMS, but the following works with the Postgres and Oracle JDBC drivers. I didn't test any other.

// the statement is only prepared, not executed!
PreparedStatement pstmt = con.prepareStatement("select * from foo");

ResultSetMetaData metaData = pstmt.getMetaData();
for (int i=1; i <= metaData.getColumnCount(); i++)
{
  System.out.println(metaData.getColumnName(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