JSqlParser——SQL语法解释器使用记录:创建SQL语句

创建SQL语句

1.创建简单的SELECT语句

通过表名创建

Select select = SelectUtils.buildSelectFromTable(new Table("TABLE1"));
System.out.println(select.toString());//SELECT * FROM TABLE1

通过表名和条件创建

Select select = SelectUtils.buildSelectFromTableAndExpressions(new Table("TABLE1"), new Column("A"), new Column("B"));
System.out.println(select.toString());//SELECT A, B FROM TABLE1

条件可以使用字符串给出

Select select = SelectUtils.buildSelectFromTableAndExpressions(new Table("TABLE1"), "a+b", "name");
System.out.println(select.toString());//SELECT a + b, name FROM TABLE1
2.创建INSERT语句
Insert insert = (Insert) CCJSqlParserUtil.parse("INSERT INTO TABLE1 (A) VALUES (1)");//此处的运行时类是Insert
insert.getColumns().add(new Column("B"));//添加列
ExpressionList expressionList = (ExpressionList) insert.getItemsList();
expressionList.getExpressions().add(new LongValue(5));
System.out.println(insert.toString());//INSERT INTO TABLE1 (A, B) VALUES (1, 5)

通过访问器添加

Insert insert = (Insert) CCJSqlParserUtil.parse("INSERT INTO TABLE1 (A) VALUES (1)");//此处的运行时类是Insert
insert.getColumns().add(new Column("B"));//添加列
insert.getItemsList().accept(new ItemsListVisitor() {
    @Override
    public void visit(SubSelect subSelect) {
    }

    @Override
    public void visit(ExpressionList expressionList) {
        expressionList.getExpressions().add(new LongValue(5));
    }

    @Override
    public void visit(MultiExpressionList multiExpressionList) {
    }
});
System.out.println(insert.toString());//INSERT INTO TABLE1 (A, B) VALUES (1, 5)
3.字符串值替换

你可能感兴趣的:(Java)