Parsing SQL Statements using java

后端 未结 5 2023
礼貌的吻别
礼貌的吻别 2021-01-06 18:44

I need to parse sql statements and get column names and table names. I tried with sample code. I got table names but I am stucked to get column names for each table.

相关标签:
5条回答
  • 2021-01-06 18:55

    What you need is an SQL parser.

    You can try JSQLParser, or ZQL.

    I have used both successfully for the same thing the you are trying to do.

    You can try also sqlparser. This is commercial however and I have no experience using it.

    0 讨论(0)
  • 2021-01-06 18:59

    Checkout Foundation Parser http://foundationdb.github.io/sql-parser/

    Also note JSQLParser is no longer on SourceForge but maintain at https://github.com/JSQLParser/JSqlParser/wiki

    0 讨论(0)
  • 2021-01-06 19:12

    If you are having ResultSet object then, you can read Column names and Table Names of fired Query.

    by using ResultSetMetaData to get MetaData of your query (like table names and column names).

    example

    0 讨论(0)
  • 2021-01-06 19:14

    If you really really need to do this then you should look at using a proper parser toolkit like ANTLR. It is quite a steep learning curve but there are grammars around for SQL that others have already built.

    Hand-cranking your own parser will lead you down a mess of bugs for anything but the most basic of queries.

    0 讨论(0)
  • 2021-01-06 19:14

    You will need to create a parser for your SQL grammar. ANTLR allows to create such parsers but it can be quite difficult to create a grammar.

    Here is a list of exisiting grammar for ANTLR http://www.antlr3.org/grammar/list.html

    It contains grammar for mysql, oracle SQL that should work for you.

    0 讨论(0)
提交回复
热议问题