java 动态拼接sql_动态SQL拼接工具类

动态SQL拼接处理工具类,为了传动态参数sql语句拼接的灵活使用。具体源代码见:

下面简单介绍下使用Demo:

public static void main(String[] args) throws IOException {

DynamicSQL dsql = new DynamicSQL();

dsql.append("SELECT s.dept_name, s.id, s.name, t.year, t.semester, t.course_id, t.grade  ");

dsql.append("  FROM student s   ");

dsql.append("  LEFT JOIN takes t ON s.id = t.id ");

dsql.append("  where s.id = '1'      ");

dsql.isNotEmpty(" and t.year = #    ", "2015");

dsql.isNotEmpty(" and t.month = #    ", "");

dsql.isEqual(" and t.semester = $  ", 2, 2);

System.out.println(dsql.getSql());

System.out.println(dsql.getParams());

System.out.println(dsql);

System.out.println("+++++++++++++++++++++++++++++++++++++++++++");

dsql.clear();

dsql.append("SELECT s.dept_name, s.id, s.name, t.year, t.semester, t.course_id, t.grade  ");

dsql.append("  FROM student s   ");

dsql.append("  LEFT JOIN takes t ON s.id = t.id ");

dsql.append("  where s.id = '1'      ");

dsql.isNotEmpty(" and t.year = #    ", "2015");

dsql.isNotEmpty(" and t.month = $    ", "");

dsql.isEqual(" and t.semester = $  ", new Integer(3), new Integer(3));

dsql.isEqual(" and t.semester2 = $  ", 5, 5);

System.out.println(dsql.getSql());

System.out.println(dsql.getParams());

System.out.println(dsql);

System.out.println("+++++++++++++++++++++++++++++++++++++++++++");

dsql.clear();

String ids = "1, 2, 3, 4, 5";

//dsql.append("delete from sdt_bdi_std_type ");

//dsql.isNotEmpty("  where id in ($) ", ids);

dsql.isNotEmpty(String.format("delete from %s where id in ($) ", "sdt_bdi_std_type"), ids);

System.out.println(dsql.getSql());

System.out.println(dsql.getParams());

System.out.println(dsql);

}

运行的结果如下:

SELECT s.dept_name, s.id, s.name, t.year, t.semester, t.course_id, t.grade FROM student s LEFT JOIN takes t ON s.id = t.id where s.id = '1' and t.year = ? and t.semester = ?

[2015, 2]

SELECT s.dept_name, s.id, s.name, t.year, t.semester, t.course_id, t.grade FROM student s LEFT JOIN takes t ON s.id = t.id where s.id = '1' and t.year = '2015' and t.semester =  2

+++++++++++++++++++++++++++++++++++++++++++

SELECT s.dept_name, s.id, s.name, t.year, t.semester, t.course_id, t.grade FROM student s LEFT JOIN takes t ON s.id = t.id where s.id = '1' and t.year = ? and t.semester2 = ?

[2015, 5]

SELECT s.dept_name, s.id, s.name, t.year, t.semester, t.course_id, t.grade FROM student s LEFT JOIN takes t ON s.id = t.id where s.id = '1' and t.year = '2015' and t.semester2 =  5

+++++++++++++++++++++++++++++++++++++++++++

delete from sdt_bdi_std_type where id in (?)

[1, 2, 3, 4, 5]

delete from sdt_bdi_std_type where id in ( 1, 2, 3, 4, 5 )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值