mybatis批量更新时sql语句没问题但报bad SQL grammar []错误

来源:互联网 发布:战龙三国周瑜进阶数据 编辑:程序博客网 时间:2024/06/10 23:36

网上对于mybaitis批量更新的实现提供了大概两种方法。一种是使用sql的case语法。另一种是每次只更新一条但是用foreach语句拼装起来。我使用的就是第二种。mybatis的语句大致如下:

<update id="setWeiboEmotionByList" parameterType="java.util.List">        <foreach collection="list" item="item" open="" close="" separator=";">            UPDATE weibo_content            SET                EMOTION = #{item.emotion}            WHERE                WEIBO_ID = #{item.weibo_id}        </foreach>    </update>

一次更新多条sql语句,每一条以分号隔开。以上mybatis翻译成sql大致如下:

UPDATE weibo_contentSET   EMOTION = 1WHERE   WEIBO_ID = 1;UPDATE weibo_contentSET   EMOTION = 0WHERE   WEIBO_ID = 2;   

但是在进行测试的时候,每次更新数据库时就会出现类似的如下错误:

Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE weibo_content            SET                EMOTION = 0.0            W' at line 7; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE weibo_content

但是我将sql语句单独放在navicat中是可以成功执行的,后来发现是连接数据库的时候少了allowMultiQueries=true 这条语句。这条语句允许一次提交多条sql语句。特别是分号;
完整的数据库连接url大致如下:
jdbc:mysql://localhost:3306/zkw_web?useUnicode=true&characterEncoding=utf8 &allowMultiQueries=true

原创粉丝点击