JDBC:获取SQL查询中涉及的表名 [英] JDBC: Get table names involved in a SQL query

查看:140
本文介绍了JDBC:获取SQL查询中涉及的表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法知道通过JDBC执行的SQL查询中涉及的表的名称?

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

例如:

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.

推荐答案

我尚未找到如何准确执行所需功能的方法,但是由于要评论太久了,我还是将其发布.我找到的最接近的东西是 ResultSetMetaData .

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.

这是有关如何获取它的教程.

但是该教程没有显示如何获取表名.执行此操作的方法称为getTableName.

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;

我认为您必须遍历所有列并将表名放在Set中.结果应该是所有使用的表,但是...问题是,如果未在选择中显示该列,那么您将无法发现该表.我还没有找到解决这个问题的方法.

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.

这篇关于JDBC:获取SQL查询中涉及的表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆