0

I want to parse a sql query and extract only column names from it. I can't just extract the part between 'select' and 'from' because the query can also have an alias. This is the requirement for now, but later on any type of query can come in, so I need a dynamic method/ library which will return the column names.

jeremyjjbrown
  • 7,772
  • 5
  • 43
  • 55
  • Note that questions asking us to recommend or find a library are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. – Dennis Meng Feb 06 '14 at 06:01
  • possible duplicate of [SQL - Parsing a query](http://stackoverflow.com/questions/1259629/sql-parsing-a-query) – Jan Doggen Feb 06 '14 at 08:56

1 Answers1

2

You need to use the ResultSetMetaData to get the names of the columns in the result set returned after executing the query.

ResultSet rs = stmt.executeQuery(...);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount()
for (int i = 1; i <= columnCount; i++) {
    System.out.println(rsmd.getColumnName(i));
}

Note: The index starts from 1 and not from 0

Vikdor
  • 23,934
  • 10
  • 61
  • 84