JDBC: Get table names involved in a SQL query

I haven't found out how to do exactly what you need but I'm going to post this anyway since it's too long to be a comment. The closest thing I've found is the ResultSetMetaData.

This is a tutorial on how to get it. But that tutorial doesn't show how to get the table names. The method to do that is called getTableName.

/**
 * Gets the designated column's table name. 
 *
 * @param column the first column is 1, the second is 2, ...
 * @return table name or "" if not applicable
 * @exception SQLException if a database access error occurs
 */
String getTableName(int column) throws SQLException;

I think you'll have to iterate through all the columns and put the table names in a Set. The result should be all the tables used but... the problem is, if the column isn't exposed in the select, then you won't be able to discover the table. I haven't been able to find a way around this.


The JSQLParser library (LGPL V2.1) seems to be capable of doing exactly what is required:

Extract table names from SQL

Statement statement = CCJSqlParserUtil.parse("SELECT * FROM MY_TABLE1");
Select selectStatement = (Select) statement;
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
List<String> tableList = tablesNamesFinder.getTableList(selectStatement);

Tags:

Sql

Java

Jdbc