问题描述: 使用如下语句时, 在最终的拼接中产生了 sql 语法错误
- <if test="conditions!=null">
- <trim prefix="AND (" prefixOverrides="OR" suffix=")">
- <foreach item="item" index="index" collection="conditions" separator="or">
- <if test="item!=null">
- ${item}
- </if>
- </foreach>
- </trim>
- </if>
错误截图:
报错截图 1
同时产生错误的完整 sql 语句:
==> Preparing: SELECT idaction_event_category AS eventCategory, idaction_event_action AS eventAction, idaction_name AS eventName, COUNT(*) AS nb_event, COUNT(DISTINCT idvisitor) AS nb_uniq_visitor, CONVERT(SUM(time_spent_ref_action)/count(*),DECIMAL) AS avg_spent_time FROM t_analytics_log_link_visit_action WHERE 1 = 1 AND idsite = ? AND idaction_event_category> 0 AND idaction_event_action> 0 AND ( (idaction_name=10478 and idaction_event_action=10476 and idaction_event_category=20962 ) or (idaction_name=20936 and idaction_event_action=10476 and idaction_event_category=20966 ) or (idaction_name=20936 and idaction_event_action=10476 and idaction_event_category=20967 ) or (idaction_name=20936 and idaction_event_action=10476 and idaction_event_category=20968 ) or (idaction_name=20936 and idaction_event_action=10476 and idaction_event_category=20969 ) or (idaction_name=20936 and idaction_event_action=10476 and idaction_event_category=20970 ) ) AND DATE(server_time)>= ? AND DATE(server_time) <= ? GROUP BY idaction_event_category, idaction_event_action, idaction_name
以上的错误, 是在解决问题后, 根据问题原因再现出来的, 产生问题的原因是:
问题代码截图 1
注意红圈内的这个空格, 这个空格是使用的全角空格, 之所以会出现全角空格因该语句为百度后从页面直接复制过来的, 这个空格来自斧子的页面. 可以在下图看到, 最终的 sql 语句中也出现了全角的空格, 最终影响了 sql 语句
问题代码截图 2
以上的空格出现在最终执行的 sql 语句中, 使得 sql 解析出现问题, 由于语法造成问题的原因并不是语法, 所以问题难以定位.
关与这个问题的启示: 在程序始终 sql 语句虽然可以自动处理多余的空格, 但是如果有全角空格, 这个全角空格在 sql 中无法被正常解析, 出现无语法错误仍然报错的现象. 即 sql 语句无法处理全角空格
关于问题的避免: 在从网罗上获取的代码段, 极有可能潜藏这种全角空格的问题, 而页面上的代码, 与编辑其中的代码纯在一些不易发现的格式问题, 都会出现类似的问题, 使用网上代码就需要注意这些代码中符号的格式问题, 另如果在 xml 编辑界面中使用了代码格式化就纠正了这个问题, 也说明了代码格式化是一种可以避免代码格式问题出现的习惯.
来源: http://www.jianshu.com/p/79276dd66f8c