3

I am in need of a java API to parse a SQL statement.

For example, I have a SQL query

SELECT
  PRODUCTS.PROD_ID,
  PRODUCTS.PROD_NAME,
  PRODUCTS.PROD_CATEGORY,
  PRODUCTS.PROD_TOTAL_ID
FROM
  PRODUCTS

I need to retrieve the table name "Products" and the column names as "Prog_ID" etc.

Please provide any links to tutorials or code snippets if possible.

1

4 Answers 4

4

ANTLR is a parser generator that has a SQL grammar, but that might be more than you bargained for.

It would be simpler to write one on your own, as long as your requirements didn't get too crazy. How general do you need to be?

Sign up to request clarification or add additional context in comments.

5 Comments

Been there done that! Parsing SQL is a bit of a nightmare -- you need to parse a specific dialect (ORACLE,SQLServer etc.). The vast number of keywords, the inconsistent syntax, the overloading of keywords means you need a massive and complex grammar.
I have a very simple requirement, the query posted above is the only format i ll be using.
@user727272, in that case, you can construct the ANTLR grammar to suit only that format, and parse it. I would suggest getting a copy of Terrence Parr's book - The Definitive ANTLR Reference, if you are finding the tutorials on the ANTLR site to be difficult.
parsing SQL is beyond a nightmare... see the post i just made: stackoverflow.com/questions/12863532/…
No wonder - you tried to mangage vendor-specific SQL with regex? Your situation sounds like a case study for "do not do this."
3

If you have a connection to the database, you can do that using a prepared statement:

String sql = "....";
PreparedStatement pstmt = connection.prepareStatement(sql);
ResultSetMetaData meta = pstmt.getMetaData();

Then you can use ResultSetMetaData.getColumnCount() and getColumnName(int) to retrieve the column names. If your JDBC driver supports it, you can even get the underlying table name using getTableName(int)

Note that not all drivers support getting the metadata before actually executing the statement, you need to test that with the one you are using.

Comments

2

Ended up using ZQL Parsing libraries from http://zql.sourceforge.net/.

If you are having simple queries , that should do the job easily

2 Comments

Please mark this as the Accepted answer unless there is better answer by now.
Does ZQL parser allow us to get table names if we have Joins?
1

Regex matching is only work for simple query, SQL has a complex recursive grammer, and, there will always be some sub select, group by, or literal that will break your regex based parser.

Here is a demo illustrates how to achieve what you need by using general sql parser:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.