采用StringBuffer来拼接sql,最开始如下写法:
StringBufer sql=new StringBufer(“update table set “);
If(getA()!=null&&!””.equals(getA()))
sql.append(“a=#a#”);
If(getB()!=null&&!””.equals(getB()))
sql.append(“,b=#b#”);
If(getC()!=null&&!””.equals(getC()))
sql.append(“,c=#c#”);
sql.append(“id=#id#”);
问题复现:当a不存在,b和c存在时,sql=update table set ,b=?,c=? where id=?; 此时报错
我的业务中b一定有值,此时改为:
StringBufer sql=new StringBufer(“update table set “);
If(getB()!=null&&!””.equals(getb()))
sql.append(“,b=#b#”);
If(getA()!=null&&!””.equals(getA()))
sql.append(“a=#a#”);
If(getC()!=null&&!””.equals(getC()))
sql.append(“,c=#c#”);
sql.append(“id=#id#”);
日志打印sql=update table set ,b=?,c=? where id=?; 感觉没有生效,此时我又改为:
StringBufer sql=new StringBufer(“update table set b=#b#“);
If(getA()!=null&&!””.equals(getA()))
sql.append(“a=#a#”);
If(getC()!=null&&!””.equals(getC()))
sql.append(“,c=#c#”);
sql.append(“id=#id#”);
日志打印sql=update table set ,b=?,c=? where id=?; 还是没有生效,最后我改成:
String str=” update table set b=#b#”;
StringBufer sql=new StringBufer(str);
If(getA()!=null&&!””.equals(getA()))
sql.append(“a=#a#”);
If(getC()!=null&&!””.equals(getC()))
sql.append(“,c=#c#”);
sql.append(“id=#id#”);
日志打印sql= update table set b=?,c=? where id=?;
终于成功。
我现在不是很清楚是什么原因造成,考虑缓存,但在测试期间把应用部署重启也没有生效,难道是StringBuffer的一些原因还是java的因素亦或者是自身应用服务器等复杂环境下造成的问题??有知道的人可以回答一下。。