Java代码构建SQL语句之jsqlparser

0、官网
1、引入依赖
    <dependencies>
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>4.7</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
    </dependencies>
2、新增
3、删除
    @Test
    public void buildDelete(){
        Delete delete = new Delete();
        delete.setTable(new Table("t_user"));
        //添加where条件
        EqualsTo equalsTo = new EqualsTo();
        equalsTo.setLeftExpression(new Column("username"));
        equalsTo.setRightExpression(new StringValue("张三"));
        delete.setWhere(equalsTo);
        //DELETE FROM t_user WHERE username = '张三'
        System.out.println(delete);
    }
4、查询
Select select = SelectUtils.buildSelectFromTable(new Table("t_user"));
        PlainSelect plainSelect = select.getPlainSelect();

        //添加where条件 =
        EqualsTo equalsTo = new EqualsTo();
        equalsTo.setLeftExpression(new Column("username"));
        equalsTo.setRightExpression(new StringValue("李四"));
        plainSelect.setWhere(equalsTo);

        //添加where条件 like
        LikeExpression likeExpression = new LikeExpression();
        likeExpression.setLeftExpression(new Column("username"));
        likeExpression.setRightExpression(new StringValue("张%"));
        plainSelect.setWhere(likeExpression);

        //添加where条件 and
        AndExpression andExpression = new AndExpression();
        andExpression.setLeftExpression(equalsTo);
        andExpression.setRightExpression(likeExpression);
        plainSelect.setWhere(andExpression);

        //添加where条件 and
        Between between = new Between();
        between.setBetweenExpressionStart(new LongValue(18));
        between.setBetweenExpressionEnd(new LongValue(30));
        between.setLeftExpression(new Column("age"));

        //添加where条件 and
        OrExpression orExpression = new OrExpression();
        orExpression.setLeftExpression(andExpression);
        orExpression.setRightExpression(between);
        plainSelect.setWhere(orExpression);

		//SELECT * FROM t_user WHERE username = '李四' AND username LIKE '张%' OR age BETWEEN 18 AND 30
        System.out.println(plainSelect);
5、修改
    @Test
    public void buildUpdate(){
        Update update = new Update();
        update.setTable(new Table("t_user"));
        //设置字段
        update.addUpdateSet(new Column("username"), new StringValue("张三"));
        update.addUpdateSet(new Column("age"), new StringValue("18"));
        //添加where条件
        EqualsTo equalsTo = new EqualsTo();
        equalsTo.setLeftExpression(new Column("username"));
        equalsTo.setRightExpression(new StringValue("李四"));
        update.setWhere(equalsTo);
		
		//UPDATE t_user SET username = '张三', age = '18' WHERE username = '李四'
        System.out.println(update);
    }

你可能感兴趣的:(Java,java,sql,开发语言)