Need Java API to parse SQL queries

I need a Java API to parse a SQL query.

For example, I have an SQL query

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

I need to get the table name “Products” and column names as “Prog_ID” etc.

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

+3
source share
4 answers

Finished using the ZQL Parsing libraries from http://zql.sourceforge.net/ .

If you have simple queries, this should make things easier.

+2
source

ANTLR is a parser generator that has SQL grammar , but it may be more than you expected.

, . ?

+4

, :

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

ResultSetMetaData.getColumnCount() getColumnName(int) . JDBC , , getTableName(int)

, , , .

+3

Regular expression matching only works for a simple query, SQL has a complex recursive grammar, and there will always be some kind of subset, group or literal that breaks your regular expression parser.

Here is a demo showing how to achieve what you need using a common sql parser:

+1
source

All Articles