Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning just column names of ResultSet without actually performing the query (Oracle and Java)

Tags:

java

oracle

I'm wondering if there is a way to return the column names of a results set (Oracle database, in Java) that would be generated IF I actually executed a query. For example, say I had SQL looking something like this:

select * from <complex table join>;

Is there a way to send this query to oracle and have it tell me just what the column names are on the result set it will return WITHOUT actually performing the query (because it is expensive)?

like image 937
mpettis Avatar asked Jan 09 '13 19:01

mpettis


People also ask

How do you get a column from a ResultSet?

You can get the name of a particular column using the getColumnName() method of the ResultSetMetadata interface. This method accepts an integer value representing the index of a column and returns a String value representing the name of the specified column.

Can we return ResultSet in Java?

Yes, just like any other objects in Java we can pass a ResultSet object as a parameter to a method and, return it from a method.

How can I determine if the column name exist in the ResultSet?

The getColumnName() method returns the name of the column of the specified index. Using this method retrieve the column names of the RowSet from index 1 to column count and compare name of the each column, with the required column name.


2 Answers

I think using a PreparedStatement could work:

PreparedStatement stmt = connection.prepareStatement("select ...");
ResultSetMetaData meta = stmt.getMetaData();
for (int col=0; col < meta.getColumnCount(); col++) 
{
   System.out.println("Column: " + meta.getColumnName(col + 1));
}

(Edit): I tried this with Oracle 11.2 and driver version 11.2.0.3 and it works.

If that fails you could simply append a where 1=0 to the query and execute it then. At least it will not return all the rows then (possibly also using Statement.setMaxRows() as well, just to be sure.

A final (yet pretty complicated) option would be to use dbms_sql to open, prepare and describe the statement. See the manual for details: http://docs.oracle.com/cd/E11882_01/appdev.112/e25788/d_sql.htm

like image 84
a_horse_with_no_name Avatar answered Nov 05 '22 09:11

a_horse_with_no_name


You could try wrapping the query in an outer select and adding where 1=0 to prevent it from fetching any rows:

  SELECT * from (
    <your query here>
  )
  WHERE 1=0
like image 41
Frank Schmitt Avatar answered Nov 05 '22 10:11

Frank Schmitt