CCJSqlParserUtil 增加where条件

package com.alibaba.kaola.ad.searchad.common.utils;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

/**
 * @author hezhenyuan
 */
public class SqlUtils {

    /**
     * 在原有的sql中增加新的where条件
     *
     * @param sql       原sql
     * @param condition 新的and条件
     * @return 新的sql
     */
    public static String addWhereCondition(String sql, String condition) {
        try {
            Select select = (Select)CCJSqlParserUtil.parse(sql);
            PlainSelect plainSelect = (PlainSelect)select.getSelectBody();
            final Expression expression = plainSelect.getWhere();
            final Expression envCondition = CCJSqlParserUtil.parseCondExpression(condition);
            if (expression == null) {
                plainSelect.setWhere(envCondition);
            } else {
                AndExpression andExpression = new AndExpression(expression, envCondition);
                plainSelect.setWhere(andExpression);
            }
            return plainSelect.toString();
        } catch (JSQLParserException e) {
            throw new RuntimeException(e);
        }
    }
}

 

@Test
public void testSql() {
    String sql = "select * from table_name";
    String newSql = SqlUtils.addWhereCondition(sql, "env='daily'");
    System.err.println(newSql);
}

 

CCJSqlParserUtil 增加where条件_第1张图片

你可能感兴趣的:(sql)