Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC: Get table names involved in a SQL query

Tags:

java

sql

jdbc

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.

like image 500
Hoffmann Avatar asked May 17 '13 18:05

Hoffmann


1 Answers

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.

like image 200
Daniel Kaplan Avatar answered Sep 30 '22 16:09

Daniel Kaplan