mybatis sql中间包含分号报错,启用sql语句批处理“&allowMultiQueries=true“解决

问题描述

我的需求是使用mybatis实现在指定数据库建表,sql如下:

	<update id="createTable">
	USE ${dbNmae};
	CREATE TABLE
	IF NOT EXISTS ${tableName} (
	<if test="sqlItems != null and sqlItems.size() > 0">
	<!-- 外层list 里面每一个元素为一个字段的组成元素 -->
	<foreach collection="sqlItems" separator=" " item="items"  index="index">
		<!-- 内层list 里面每一个都是字段sql语句的一部分 -->
		<foreach collection="items" separator=" " item="item"  index="ind">
				<if test="ind == 0">
					${item}
				</if>
				<if test="ind == 1">
					${item}
				</if>
				<if test="ind == 2">
					(${item})
				</if>
				<if test="ind == 3 and 'No' eq item">
					NOT NULL
				</if>
				<if test="ind == 4 and 'Yes' eq item ">
					PRIMARY KEY
				</if>
				
		</foreach>
		<if test="index != sqlItems.size() -1 ">
		,
		</if>
	</foreach>
	</if>
	) ENGINE = INNODB DEFAULT CHARSET = utf8;
	</update>

然而程序报错了

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 'CREATE TABLE

检查控制台打印出来的sql语句,发现并没有问题,在本地是可以顺利在指定数据库建表的

==>  Preparing: USE des_db; CREATE TABLE IF NOT EXISTS demo ( dId int (10) NOT NULL PRIMARY KEY , name varchar (20) ) ENGINE = INNODB DEFAULT CHARSET = utf8; 

问题所在

USE ${dbNmae};
CREATE TABLE
...
...

mybatis默认不开启sql语句的批处理,上面的分号“;”mybatsi不识别,所以会报错

解决方案

我所使用的方案:在数据库连接上加上“&allowMultiQueries=true” ,如

url: jdbc:mysql://localhost:3306/des_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true

还有其他解决方案,例如修改动态sql使得sql语句变成一条

参考:mybatis 拼接sql 语句中不能出现“;”(分号),也就是不能多次执行。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值