2017  Kodetalk | Feedback | Privacy Policy | Terms | About

How to parse a dynamic SQL string using java code

I am trying develop a editor and want parse SQL string given by user. I want parse that SQL string like want to validate or may be dynamically adding new alias for selected column based on user response. How can i do the best. I am trying to do manually but i do believe like i may skip some part so want to use some API. Is there any default API that i can use in my project.


For doing operation on SQL statements you can use below API. I believe it's a good API to parse SQL statements:






Example code:

package com.sql.test;

import java.util.List;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.Statements;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.util.AddAliasesVisitor;
import net.sf.jsqlparser.util.SelectUtils;
import net.sf.jsqlparser.util.TablesNamesFinder;

 * @author debs 28 December 2016
public class ParseSQLQuery {
	public static void main(String[] args) {
		try {

			// Getting a simple statement and parsing
			Statement statement = CCJSqlParserUtil.parse("SELECT * FROM USER_TABLE");
			Select selectStatement = (Select) statement;
			TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
			List<String> tableList = tablesNamesFinder.getTableList(selectStatement);

			System.out.println("Table Name : " + tableList);

			Select select = (Select) CCJSqlParserUtil.parse("select a,b,c from TEST_TABLE");
			final AddAliasesVisitor instance = new AddAliasesVisitor();

			System.out.println("The changed select statement is : " + select);

			Statements stmt = CCJSqlParserUtil.parseStatements("SELECT * FROM TABLE1; SELECT * FROM TABLE2");

			System.out.println("Multiple select statement : " + stmt);

			Select selects = (Select) CCJSqlParserUtil.parse("select a from NEWTABLE");
			SelectUtils.addExpression(selects, new Column("b"));

			System.out.println("After adding a new select column : " + selects);
		} catch (JSQLParserException e) {
Answer is