简体   繁体   中英

Can I get a table name from a join select resultset metadata

Below is my code trying to retrieve table name form Resultset

ResultSet rs = stmt.executeQuery("select * from product");

ResultSetMetaData meta = rs.getMetaData();
int count = meta.getColumnCount();
for (int i=0; i<count; i++) {
  System.out.println(meta.getTableName(i));
}

But it returns empty, no mention it is a join select resultset. Is there any other approaches to retrieve table name from reusltset metadata?

Getting table names from ResultSetMetaData is something most DBMS's JDBC-drivers (Oracle, DB2,...) don't imlement since there are many situations where the specification doesn't define what should be returned - eg in case of views (view-name or base-table-name), presence of aliases (table-alias or real table-name), results of functions that take multiple or no parameters etc.

So I fear there is no way to get what you want for most DBMSs, least of all in a DBMS-independent manner.

When you create you statement, try setting the scroll/concurrency types like so: conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY)

Some drivers require these settings in order to return the table name.

See here for details

The column indices passed to getTableName() start at 1. Change your loop to read:

for (int i=1; i<=count; i++) {
  System.out.println(meta.getTableName(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