欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > Cause: java.sql.SQLException: No value specified for parameter 4

Cause: java.sql.SQLException: No value specified for parameter 4

2025/4/21 0:24:20 来源:https://blog.csdn.net/wangjun5159/article/details/144132984  浏览:    关键词:Cause: java.sql.SQLException: No value specified for parameter 4

问题

执行更新sql时报错,异常栈如下

org.springframework.jdbc.BadSqlGrammarException: 
### Error updating database.  Cause: java.sql.SQLException: No value specified for parameter 4
### The error may exist in com/my/mapper/MyMapper.java (best guess)
### The error may involve com.my.mapper.MyMapper.updateById-Inline
### The error occurred while setting parameters
### SQL: UPDATE my_table  SET col1=?, col2=?, col3=?,   col4=? WHERE id=?
### Cause: java.sql.SQLException: No value specified for parameter 4
; bad SQL grammar []; nested exception is java.sql.SQLException: No value specified for parameter 4
Statement [truncated]: UPDATE my_table  SET col1='xxx',\ncol2='',\ncol3='',\n\n\ncol4=null

注意,占位符索引是从1开始的,所以这里的parameter 4,是col4;提示信息是未设置col4;

col4字段,数据类型是个json格式的字符串,数据类型是varchar(设置为json更合理),为了查询出来字符串自动转为对象;更新数据时,将对象转为字符串;所以自定义了Mybatis的BaseTypeHandler

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
@MappedJdbcTypes({JdbcType.LONGVARCHAR})
@MappedTypes({List.class})
public class CustomTypeHandler extends BaseTypeHandler<List<CustomInfo>> {@Overridepublic void setNonNullParameter(PreparedStatement preparedStatement, int i, List<CustomInfo> customInfos, JdbcType jdbcType) throws SQLException {if (customInfos == null || customInfos.isEmpty() || !JdbcType.LONGVARCHAR.equals(jdbcType)) {return;}String str = JSON.toJSONString(customInfos);preparedStatement.setString(i, str);}}

解决

根据提示信息,自然而然的就知道,需要设置下值
修改后

if (customInfos == null || customInfos.isEmpty() || !JdbcType.LONGVARCHAR.equals(jdbcType)) {//没有值或者空集合,根据实际情况,设置为nullpreparedStatement.setString(i,null);return;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词