JDBC: Get table names involved in a SQL query

∥☆過路亽.° 提交于 2021-01-27 04:46:14

问题


Is there any way to know the name of the tables involved in a SQL query executed via JDBC?

For example:

SELECT r.roleId FROM User u, UserRole r where r.userId = u.userId and u.name = "Jonh Smith"

I don't want only the result set of this query but the actual table names ("User" and "Role"). I don't care about view names, but if there is no way to get the underlying table used in the view it's not a big problem, but this has to work with nested queries.

As for why I need this information it's because I am making a platform that lets other developers build applications on top of it. In my platform I let other developers register their own queries and I store them in a database. I don't want the developers to have to bother with actually manually registering the table names along with the query itself. So at the time I am executing the query I do not really know what that query is doing.


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/16616034/jdbc-get-table-names-involved-in-a-sql-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!