error:
Cause: java.sql.SQLSyntaxErrorException: 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 '' at line 1
### Error updating database. Cause: java.sql.SQLSyntaxErrorException: 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 '' at line 1
### The error may exist in file [D:\Software\工作\study\easy-excel\target\classes\mapper\GoodsDao.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: insert into goods (goods_name, price) values
### Cause: java.sql.SQLSyntaxErrorException: 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 '' at line 1
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: 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 '' at line 1] with root cause
java.sql.SQLSyntaxErrorException: 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 '' at line 1
解决的过程:
- xml中的sql语句如下:
<insert id="save" parameterType="java.util.List">
insert into goods (goods_name, price) values
<foreach collection="list" item="dataList" index="index" separator=",">
(
#{dataList.goods_name},
#{dataList.price}
)
</foreach>
</insert>
- dao接口
public interface GoodsDao {
void save(@Param("list") List<Goods> list);
}
- easyExcel读取excel监听器
public class GoodsExcelReadListener extends AnalysisEventListener<Goods> {
private GoodsDao goodsDao;
//如果此处需要使用Spring管理的类,需要通过构造函数的方式将spring管理的类传进来
public GoodsExcelReadListener(GoodsDao goodsDao){
this.goodsDao =goodsDao;
}
private static final int BATCH_COUNT = 5;//实际可以用3000,方便回收内存
private List<Goods> list = new ArrayList<>();
@Override
public void invoke(Goods goods, AnalysisContext analysisContext) {
list.add(goods);
if(list.size()>=BATCH_COUNT){
goodsDao.save(list);
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
goodsDao.save(list);
}
- 首先想到的是mapper.xml中的sql语句有问题,因为这个提示不是很明显,所以想到的是可能sql语句写的有问题,但是仔细检查了发现写的并没有毛病。
- 又试了试不从excel读取数据,模拟一个list集合然后批量插入,发现可以正常插入。
- 定位就是easyExcel读取那块插入出现问题。
- 翻了一下监听器那块,找到了问题 问题就出在了doAfterAllAnalysed这个方法。
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
goodsDao.save(list);
}
初学easyExcel这个工具,之前测试的时候没有涉及数据库操作,一直都是模拟打印。然后这个方法会在excel当前sheet所有行的数据读取完后执行,我的本意是插入剩余的数据。但是我每次批量保存的数据是5条,我excel里面一共放了20条数据,所以刚好4次就插入完了,所以执行到这里的时候list集合是没有数据的,插入的时候就造成了文初的那个报错。所以这里要加一个判断。
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
if(list.size()>0) {
goodsDao.save(list);
}
}
大意了,,,
总结:
当mybatis批量插入出现 Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax;这种异常时,不一定就是mapper.xml中的sql语句写的有问题。也有可能是插入的集合为空造成的。