JsqlParser插件用来对于SQL语句进行解析和组装,将SQL语句关键词之间的内容用List
JsqlParser其实就是将sql语句各个关键词用Java类的形式进行了对应解析,包括很多函数可以让我们得到各个部分的内容。我目前只是简单的测试使用,更深入的实现,比如javacc语法树没有了解太多。很简单的东西,主要是关于JsqlParser类型转换总结。
Parsing类以及其中函数说明:
各个函数都有说明,参数Sting sql,得到List
TableNameFinder类多注意一些,很好使用,任何类型的SQL语句、无论是否包含嵌套SQL 此类的静态函数都能将table name提取出来,后面直接使用String replace函数进行替换即可。
不过有个bug,就是tablenamefinder只能得到所有不重复的表名tablename,如果发生重复只能得到一个,不能重复获取,没找到源码出现这种情况的原因,留待以后学习多了再进行解决。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.Join;
import net.sf.jsqlparser.statement.select.OrderByElement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectItem;
import net.sf.jsqlparser.statement.update.Update;
import net.sf.jsqlparser.util.TablesNamesFinder;
public class Prasing_Test {
//三个 sql语句 测试例子,select,insert,update
//由已知的 sql语句 分别得到对应的 List 或 String
public static void test_select(String sql) throws JSQLParserException {
// *********select body items内容
List str_items = Prasing_Test.test_select_items(sql);
// **********select table
List tableList = Prasing_Test.test_select_table(sql);
// **********select table with join
List tablewithjoin = Prasing_Test.test_select_join(sql);
// // *******select where
String str = Prasing_Test.test_select_where(sql);
// // ******select group by
List str_groupby = Prasing_Test.test_select_groupby(sql);
// //**************select order by
List str_orderby = Prasing_Test.test_select_orderby(sql);
}
public static void test_insert(String sql) throws JSQLParserException {
// ****insert table
String string_tablename = Prasing_Test.test_insert_table(sql);
// ********* insert table column
List str_column = test_insert_column(sql);
// ********Insert values ExpressionList强制转换,参见InsertTest.java
List str_values = test_insert_values(sql);
}
public static void test_update(String sql) throws JSQLParserException {
// *********update table name
List str_table = test_update_table(sql);
// *********update column
List str_column = test_update_column(sql);
// *********update values
List str_values = test_update_values(sql);
// *******uodate where
String str_where = test_update_where(sql);
}
// *********select body items内容
public static List test_select_items(String sql)
throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plain = (PlainSelect) select.getSelectBody();
List selectitems = plain.getSelectItems();
List str_items = new ArrayList();
if (selectitems != null) {
for (int i = 0; i < selectitems.size(); i++) {
str_items.add(selectitems.get(i).toString());
}
}
return str_items;
}
// **********select table
// **********TablesNamesFinder:Find all used tables within an select
public static List test_select_table(String sql)
throws JSQLParserException {
Statement statement = (Statement) CCJSqlParserUtil.parse(sql);
Select selectStatement = (Select) statement;
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
List tableList = tablesNamesFinder
.getTableList(selectStatement);
return tableList;
}
//******************* select join
public static List test_select_join(String sql)
throws JSQLParserException {
Statement statement = (Statement) CCJSqlParserUtil.parse(sql);
Select selectStatement = (Select) statement;
PlainSelect plain = (PlainSelect) selectStatement.getSelectBody();
List joinList = plain.getJoins();
List tablewithjoin = new ArrayList();
if (joinList != null) {
for (int i = 0; i < joinList.size(); i++) {
tablewithjoin.add(joinList.get(i).toString());
//注意 , leftjoin rightjoin 等等的to string()区别
}
}
return tablewithjoin;
}
// *******select where
public static String test_select_where(String sql)
throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plain = (PlainSelect) select.getSelectBody();
Expression where_expression = plain.getWhere();
String str = where_expression.toString();
return str;
}
// ******select group by
public static List test_select_groupby(String sql)
throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plain = (PlainSelect) select.getSelectBody();
List GroupByColumnReferences = plain
.getGroupByColumnReferences();
List str_groupby = new ArrayList();
if (GroupByColumnReferences != null) {
for (int i = 0; i < GroupByColumnReferences.size(); i++) {
str_groupby.add(GroupByColumnReferences.get(i).toString());
}
}
return str_groupby;
}
// **************select order by
public static List test_select_orderby(String sql)
throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plain = (PlainSelect) select.getSelectBody();
List OrderByElements = plain.getOrderByElements();
List str_orderby = new ArrayList();
if (OrderByElements != null) {
for (int i = 0; i < OrderByElements.size(); i++) {
str_orderby.add(OrderByElements.get(i).toString());
}
}
return str_orderby;
}
// ****insert table
public static String test_insert_table(String sql)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Insert insertStatement = (Insert) statement;
String string_tablename = insertStatement.getTable().getName();
return string_tablename;
}
// ********* insert table column
public static List test_insert_column(String sql)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Insert insertStatement = (Insert) statement;
List table_column = insertStatement.getColumns();
List str_column = new ArrayList();
for (int i = 0; i < table_column.size(); i++) {
str_column.add(table_column.get(i).toString());
}
return str_column;
}
// ********* Insert values ExpressionList
public static List test_insert_values(String sql)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Insert insertStatement = (Insert) statement;
List insert_values_expression = ((ExpressionList) insertStatement
.getItemsList()).getExpressions();
List str_values = new ArrayList();
for (int i = 0; i < insert_values_expression.size(); i++) {
str_values.add(insert_values_expression.get(i).toString());
}
return str_values;
}
// *********update table name
public static List test_update_table(String sql)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Update updateStatement = (Update) statement;
List update_table = updateStatement.getTables();
List str_table = new ArrayList();
if (update_table != null) {
for (int i = 0; i < update_table.size(); i++) {
str_table.add(update_table.get(i).toString());
}
}
return str_table;
}
// *********update column
public static List test_update_column(String sql)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Update updateStatement = (Update) statement;
List update_column = updateStatement.getColumns();
List str_column = new ArrayList();
if (update_column != null) {
for (int i = 0; i < update_column.size(); i++) {
str_column.add(update_column.get(i).toString());
}
}
return str_column;
}
// *********update values
public static List test_update_values(String sql)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Update updateStatement = (Update) statement;
List update_values = updateStatement.getExpressions();
List str_values = new ArrayList();
if (update_values != null) {
for (int i = 0; i < update_values.size(); i++) {
str_values.add(update_values.get(i).toString());
}
}
return str_values;
}
// *******update where
public static String test_update_where(String sql)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Update updateStatement = (Update) statement;
Expression where_expression = updateStatement.getWhere();
String str = where_expression.toString();
return str;
}
public static void select_fromtxt() throws Exception {
@SuppressWarnings("resource")
BufferedReader reader = new BufferedReader(
new FileReader(
"D:\\java:eclipse\\workspace for javaSE\\JSql-test\\src\\test\\select_simple.txt"));
List statement_list = new ArrayList();
while (true) { // 输出所有语句
String line = reader.readLine();
if (line == null) {
break;
} else
statement_list.add(line);
}
for (int i = 0; i < 1; i++) {
Prasing_Test.test_select(statement_list.get(i));
}
}
public static void insert_fromtxt() throws Exception {
@SuppressWarnings("resource")
BufferedReader reader = new BufferedReader(
new FileReader("文件位置"));
List statement_list = new ArrayList();
while (true) { // 输出所有语句
String line = reader.readLine();
if (line == null) {
break;
} else
statement_list.add(line);
}
for (int i = 0; i < 1; i++) {
Prasing_Test.test_insert(statement_list.get(i));
}
}
public static void update_fromtxt() throws Exception {
@SuppressWarnings("resource")
BufferedReader reader = new BufferedReader(
new FileReader(
"D:\\java:eclipse\\workspace for javaSE\\JSql-test\\src\\test\\update_simple.txt"));
List statement_list = new ArrayList();
while (true) { // 输出所有语句
String line = reader.readLine();
if (line == null) {
break;
} else
statement_list.add(line);
}
for (int i = 0; i < 1; i++) {
Prasing_Test.test_update(statement_list.get(i));
}
}
}
building类函数
参数String sql以及修改过后的List重新得到SQl语句
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.Join;
import net.sf.jsqlparser.statement.select.OrderByElement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectExpressionItem;
import net.sf.jsqlparser.statement.select.SelectItem;
import net.sf.jsqlparser.statement.update.Update;
import net.sf.jsqlparser.util.TablesNamesFinder;
public class Building_test {
// 由已知的List 或 String 组装成新的 sql 语句
// 下面是 三个 sql语句 测试例子,select,insert,update
public static void build_select(String sql) throws JSQLParserException {
String change_sql = sql;
// *********change body items
List str_items = new ArrayList();
str_items.add("school");
str_items.add("teacher");
change_sql = build_select_items(change_sql, str_items);
// ********************change table only use " , " as join such as (from table1,table2,table3)
// List str_table =new ArrayList();
// str_table.add("preson1");
// str_table.add("preson2");
// str_table.add("preson3");
// change_sql = build_select_table(change_sql, str_table);
// ********************change table with join such as(from tb1 join tb2 left join tb3 right join tb4)
List str_table =new ArrayList();
str_table.add("preson1");
str_table.add("preson2");
str_table.add("preson3");
str_table.add("preson4");
List str_tablewithjoin =new ArrayList();
str_tablewithjoin.add("preson1");
str_tablewithjoin.add("LEFT JOIN preson2");
str_tablewithjoin.add("RIGHT JOIN preson3");
str_tablewithjoin.add("preson4");
change_sql=Building_test.build_select_tablewithjoin(change_sql,str_tablewithjoin,str_table);
// ******************select where
String str_where = "name like 'abc'";
change_sql = build_select_where(change_sql, str_where);
// ******select group by
List str_groupby = new ArrayList();
str_groupby.add("studentname");
str_groupby.add("studentid");
change_sql = build_select_groupby(change_sql, str_groupby);
// **************select order by
List str_orderby = new ArrayList();
str_orderby.add("name asc");// asc默认不显示
str_orderby.add("id desc");
change_sql = build_select_orderby(change_sql, str_orderby);
System.out.println("final:" + change_sql);
}
public static void build_insert(String sql) throws JSQLParserException {
String change_sql = sql;
// *******insert table
String str_table = "teacher";
change_sql = build_insert_table(change_sql, str_table);
// ********* insert column
List str_column = new ArrayList();
str_column.add("school");
str_column.add("city");
change_sql = build_insert_column(change_sql, str_column);
// ********* insert value
List str_value = new ArrayList();
str_value.add("'s'");
str_value.add("6");
change_sql = build_insert_values(change_sql, str_value);
// System.out.println("final:" + change_sql);
}
public static void build_update(String sql) throws JSQLParserException {
String change_sql = sql;
// *********update table name
List str_table = new ArrayList();
str_table.add("yourtable");
str_table.add("mytable");
change_sql = build_update_table(change_sql, str_table);
// *********update column
List str_column = new ArrayList();
str_column.add("col4");
str_column.add("col5");
str_column.add("col6");
change_sql = build_update_column(change_sql, str_column);
// *********update values
List str_values = new ArrayList();
str_values.add("'seemlike'");
str_values.add("'cdc'");
str_values.add("555");
change_sql = build_update_values(change_sql, str_values);
// *******update where
String str_where = "id like '3'";
change_sql = build_update_values(change_sql, str_where);
// System.out.println("final:" + change_sql);
}
// *********change body items
public static String build_select_items(String sql, List str_items)
throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
// 改写 selectitems 由 List 类型转化为 selectitem 格式的函数
select = Building_test.buildSelectFromStringExpressions(select,
str_items);
return select.toString();
}
// 原函数为SelectUtils.buildSelectFromTableAndExpressions
public static Select buildSelectFromStringExpressions(Select select,
List expr) throws JSQLParserException {
SelectItem[] list = new SelectItem[expr.size()];
PlainSelect plain = (PlainSelect) select.getSelectBody();
plain.setSelectItems(null); // empty the existing selectitems
for (int i = 0; i < expr.size(); i++) {
list[i] = new SelectExpressionItem(
CCJSqlParserUtil.parseExpression(expr.get(i)));
plain.addSelectItems(list[i]);
}
select.setSelectBody(plain);
return select;
}
// ********************change table only use " , " as join such as (from table1,table2,table3)
//**************notice*********parsing sql use function:test_select_table(sql) get List
public static String build_select_table(String sql, List str_table)
throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plain = (PlainSelect) select.getSelectBody();
plain.setFromItem(null);
plain.setJoins(null);
Listselect_join =new ArrayList();
if(str_table.size()==1){
plain.setFromItem(new Table(str_table.get(0)));
}
for(int i=0;i=2;){ //no i++
Join obj_join= new Join();
if (i==0) plain.setFromItem(new Table(str_table.get(0)));
obj_join.setSimple(true); //假定所有表的连接均为,——内连接
i++;
obj_join.setRightItem(new Table(str_table.get(i)));
select_join.add(obj_join);
}
plain.setJoins(select_join);
// plain.setForUpdateTable(new Table(str_table));
return select.toString();
}
// ********************change table with join such as(from tb1 join tb2 left join tb3 right join tb4)
//**************notice*********parsing use function:test_select_join(sql) get List
public static String build_select_tablewithjoin(String sql, List str_tablewithjoin,List str_table)
throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plain = (PlainSelect) select.getSelectBody();
plain.setFromItem(null);
plain.setJoins(null);
Listselect_join =new ArrayList();
if(str_tablewithjoin.size()==1){
plain.setFromItem(new Table(str_table.get(0)));
}
for(int i=0;i=2;){ //no i++
Join obj_join= new Join();
if (i==0) plain.setFromItem(new Table(str_table.get(0)));
i++;
String judge=str_tablewithjoin.get(i).substring(0, 3);
//这里的判断还不够充分,繁琐;;还有bug、和table name冲突
if(judge.equals("LEF")) {obj_join.setLeft(true);}
else if(judge.equals("RIG")) obj_join.setRight(true);
else if(judge.equals("INN")) obj_join.setInner(true);
else if(judge.equals("OUT")) obj_join.setOuter(true);
else if(judge.equals("FUL")) obj_join.setFull(true);
// else obj_join.setSimple(true); //tb1 , tb2 == tb1 JOIN tb2
obj_join.setRightItem(new Table(str_table.get(i)));
select_join.add(obj_join);
}
plain.setJoins(select_join);
// plain.setForUpdateTable(new Table(str_table));
return select.toString();
}
// ********************change where
public static String build_select_where(String sql, String str_where)
throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plain = (PlainSelect) select.getSelectBody();
// parseCondExpression函数 不会被空格截断
Expression where_expression = (Expression) (CCJSqlParserUtil
.parseCondExpression(str_where));
plain.setWhere(where_expression);
return select.toString();
}
// ********************change group by
public static String build_select_groupby(String sql,
List str_groupby) throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plain = (PlainSelect) select.getSelectBody();
List GroupByColumnReferences = new ArrayList();
for (int i = 0; i < str_groupby.size(); i++) {
GroupByColumnReferences.add(CCJSqlParserUtil
.parseExpression(str_groupby.get(i)));
}
plain.setGroupByColumnReferences(GroupByColumnReferences);
return select.toString();
}
// ********************change order by
public static String build_select_orderby(String sql,
List str_orderby) throws JSQLParserException {
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plain = (PlainSelect) select.getSelectBody();
List OrderByElements = new ArrayList();
for (int i = 0; i < str_orderby.size(); i++) {
OrderByElement obj_OrderbyElement = new OrderByElement(); // build
// Element类实例放在循环内部,后面得到新的element实例
String str = str_orderby.get(i);
int k = str.length() - 3;
char char_final = str.charAt(k);
Expression orderby_expression = (Expression) (CCJSqlParserUtil
.parseExpression(str));
// 实例初始化,赋值expression以及boolean asc
obj_OrderbyElement.setExpression(orderby_expression);
if (char_final == 'a')
obj_OrderbyElement.setAsc(true); // asc默认不显示
else
obj_OrderbyElement.setAsc(false);
// element加入到list中去
OrderByElements.add(obj_OrderbyElement);
}
plain.setOrderByElements(OrderByElements);
return select.toString();
}
// *******insert table
public static String build_insert_table(String sql, String str_table)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Insert insertStatement = (Insert) statement;
insertStatement.setTable(new Table(str_table));
return insertStatement.toString();
}
// ********* insert column
public static String build_insert_column(String sql, List str_column)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Insert insertStatement = (Insert) statement;
List insert_column = new ArrayList();
for (int i = 0; i < str_column.size(); i++) {
insert_column.add((Column) CCJSqlParserUtil
.parseCondExpression(str_column.get(i)));
}
insertStatement.setColumns(insert_column);
return insertStatement.toString();
}
// ********* insert values
public static String build_insert_values(String sql, List str_value)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Insert insertStatement = (Insert) statement;
List insert_values_expression = new ArrayList();
for (int i = 0; i < str_value.size(); i++) {
insert_values_expression.add((Expression) CCJSqlParserUtil
.parseExpression(str_value.get(i)));
}
// list to expressionlist to Itemlist
insertStatement.setItemsList(new ExpressionList(
insert_values_expression));
return insertStatement.toString();
}
public static String build_update_table(String sql, List str_table)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Update updateStatement = (Update) statement;
List update_table = new ArrayList();
for (int i = 0; i < str_table.size(); i++) {
Table tabletest = new Table(); // string to Table
tabletest.setName(str_table.get(i));
update_table.add(tabletest);
}
updateStatement.setTables(update_table);
return updateStatement.toString();
}
// *********update column
public static String build_update_column(String sql, List str_column)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Update updateStatement = (Update) statement;
List update_column = new ArrayList();
for (int i = 0; i < str_column.size(); i++) {
update_column.add((Column) CCJSqlParserUtil
.parseExpression(str_column.get(i)));
}
updateStatement.setColumns(update_column);
return updateStatement.toString();
}
// *********update values
public static String build_update_values(String sql, List str_values)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Update updateStatement = (Update) statement;
List update_values = new ArrayList();
for (int i = 0; i < str_values.size(); i++) {
update_values.add((Expression) CCJSqlParserUtil
.parseExpression(str_values.get(i)));
}
updateStatement.setExpressions(update_values);
return updateStatement.toString();
}
// *******update where
public static String build_update_values(String sql, String str_where)
throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse(sql);
Update updateStatement = (Update) statement;
Expression where_expression = (Expression) (CCJSqlParserUtil
.parseCondExpression(str_where));
updateStatement.setWhere(where_expression);
return updateStatement.toString();
}
}
转载自:作者:cuixuange
来源:CSDN
原文:https://blog.csdn.net/u014297722/article/details/53256533
版权声明:本文为博主原创文章,转载请附上博文链接!