使用JDBC报错“Parameter index out of range (2 > number of parameters, which is 1).“

这篇博客主要讨论了在使用JDBC的PreparedStatement时遇到的异常情况。错误信息表明在SQL语句中参数数量与实际设置的值不匹配,导致参数索引越界。解决方案是检查并确保SQL语句中的问号数量与设置的参数数量一致,从而避免此类异常的发生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异常

在使用JDBC的PreparedStatement的时候报错:

Exception in thread "main" java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:862)
	at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3319)
	at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3304)
	at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3341)
	at com.mysql.jdbc.PreparedStatement.setLong(PreparedStatement.java:3358)
	at com.mysql.jdbc.PreparedStatement.setObject(PreparedStatement.java:3529)
	at com.mysql.jdbc.JDBC42PreparedStatement.setObject(JDBC42PreparedStatement.java:68)
	at com.demo.bean.dao.BaseMapper.updateById(BaseMapper.java:289)
	at com.demo.bean.dao.Test.main(BaseMapper.java:143)

原因

根据堆栈跟踪信息提示:在SQL语句中找到了1个问号,即"which is 1"提示的信息;但却插入了2个值,即"2 > number of parameters"提示的信息,所以有问题。

也就是说发生错误的原因是当设置参数时,没有相应的问号与之匹配,然后导致参数越界。

 查看SQL语句,确实只有一个问号,所以要传入正确的SQL语句。

解决

传入正确的SQL语句,即添加对应参数个数的问号。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值