java-How to parse sql columns with JDBC or jSqlParser ?
1. The purpose of this post
This post would demo how to parse sql column names with JDBC or jSqlParser.
3. The code
3.1 The database table environment
Assume that we have a table named tbl_city, which has two column names like this:
3.2 Parse column names with JDBC
The most easiest way is to execute the sql and get the columns from the ResultSetMetaData.
Execute the code and we get this result:
3.2 Parse with jSqlParser library
But what if we don’t want to execute the sql , or we can’t execute the sql, how to parse sql column names without execute it?
You can try the jSqlParser library.
3.2.1 Add the dependency
3.2.2 The Utility Method
3.2.3 Now we test it
Run the code we got this:
As you can see, the jSqlParser can parse the sql columns without executing it, but if you do not specify the column names in your sql, for example, select * from test, it can not get the right column names. So ,use it with caution.
You can parse the sql columns with JDBC, if you choose this way, you must execute the sql on the database, then you would get the real column names. If you can’t or don’t want to execute the sql ,you can try the jSqlParser library. But use it with caution.