拿Java给SQL传参本来使用占位符“?”,按顺序站位即可。
select * from TABLE where status = ?;
如果传入参数有值,且位置在where后,那么sql语句这么写(status列为例):
select * from TABLE where status = '任意值';
——————————————————————————————————————————————
但由于本人项目中的参数可能为空,因此做了以下修改:
如果传入参数为空,且位置在where后,那么即为查询该列全部信息,此时的sql语句可以这么写:
select * from TABLE where status = status;
那么我们对于可以是空值的入参status进行如下判断赋值
if (status == null || status.length() == 0) {
status = Constants.defaultStatus;
} else if (StringUtils.isNotEmpty(status)) {
status = "'" + status + "'";
}
defaultStatus定义为字符串"status"
public final static String defaultStatus="status";
**
然后传入的sql这么拼接来写:
**
String sql = "select * from Table where status =" + status ;
这样写了之后,这条sql的status入参如果为空就是
select * from Table where status = status
如果非空,就是带引号的sql,有条件查询
select * from Table where status = '任意值'