使用JSQLParser解析SQL中涉及到的表

首先添加Maven依赖:

<dependency>
	<groupId>com.github.jsqlparser</groupId>
	<artifactId>jsqlparser</artifactId>
	<version>1.2</version>
</dependency>

然后使用下面的样例进行测试:

package com.zifeiy.test.sqlaffair;


import java.util.Iterator;
import java.util.List;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.util.TablesNamesFinder;

public class JSqlParserTest {
	public static void test(String sql) throws JSQLParserException {
		Statement statement = CCJSqlParserUtil.parse(sql);
		Select selectStatement = (Select) statement;
		TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
		List tableList = tablesNamesFinder.getTableList(selectStatement);
		for (Iterator iter = tableList.iterator(); iter.hasNext();) {
			String tableName = (String) iter.next();
			System.out.println(tableName);
		}
	}
	
	public static void main(String[] args) throws JSQLParserException {
		test("select a.c1,b.c2,c.* from tbl_a a left join tbl_b b on a.c3=b.c3 left join tbl_c c on a.c4=b.c4 where c.c5='tbl_d'");
	}
}

输出结果如下:

tbl_a
tbl_b
tbl_c

可以看到,这个样例成功地获得了SQL:

select a.c1,b.c2,c.* from tbl_a a left join tbl_b b on a.c3=b.c3 left join tbl_c c on a.c4=b.c4 where c.c5='tbl_d

中使用了 tbl_atbl_btbl_c 这三张表。

参考链接:

posted @ 2019-02-12 11:24  zifeiy  阅读(6917)  评论(0编辑  收藏  举报