[英]JDBC: Get table names involved in a SQL query
Is there any way to know the name of the tables involved in a SQL query executed via JDBC?有没有办法知道通过 JDBC 执行的 SQL 查询中涉及的表的名称?
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.
所以在我执行查询时,我真的不知道该查询在做什么。
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 .
我发现的最接近的是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
.执行此操作的方法称为
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
.我认为您必须遍历所有列并将表名放入
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: JSQLParser库 (LGPL V2.1) 似乎能够完全满足要求:
Extract table names from SQL 从 SQL 中提取表名
Statement statement = CCJSqlParserUtil.parse("SELECT * FROM MY_TABLE1");
Select selectStatement = (Select) statement;
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
List<String> tableList = tablesNamesFinder.getTableList(selectStatement);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.