You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PreparedStatement遇SQLException:参数索引越界问题求助

解决PreparedStatement的Parameter index out of range异常问题

嗨,别着急,我来帮你排查下这个问题~你遇到的SQLException: Parameter index out of range (1 > number of parameters, which is 0)异常,主要是代码里两个小错误导致的:

错误原因分析

  • 错误1:SQL占位符被单引号包裹
    你写的SQL语句里把问号放在了单引号里:"select nombre from DatosPersonas where nombre = '?'",这会让数据库把'?'当成一个普通的字符串字面量,而不是PreparedStatement的参数占位符。所以PreparedStatement会认为这条SQL没有需要绑定的参数,当你调用pstmt.setString(1, nom)时,自然就会提示参数索引越界。
  • 错误2:调用executeQuery时传入了SQL语句
    你已经通过cn.prepareStatement(query)把SQL语句绑定到了PreparedStatement对象上,调用executeQuery()的时候不需要再传入query参数。如果传了参数,相当于重新执行一条普通的SQL查询,之前绑定的参数根本没生效。

修正后的代码

String query = "select nombre from DatosPersonas where nombre = ?"; // 去掉问号的单引号
System.out.println("Introduce nomber a buscar");
String nom = teclado.next();
PreparedStatement pstmt = cn.prepareStatement(query); // 不需要强制转换,prepareStatement本身返回PreparedStatement
pstmt.setString(1, nom);
ResultSet rs1 = pstmt.executeQuery(); // 不要传入query参数
while (rs1.next()) {
    String nombre = rs1.getString("nombre");
    System.out.println(nombre);
}
// 记得最后要关闭资源哦,比如rs1、pstmt、cn,避免内存泄漏

新手使用PreparedStatement小提示

  • 占位符?不需要加任何引号,不管是字符串还是数字类型,PreparedStatement会自动帮你处理类型转换和SQL注入防护。
  • 参数索引是从1开始的,不是0,这点和数组不一样,别搞混啦~
  • 用完数据库资源(ResultSet、PreparedStatement、Connection)一定要记得关闭,最好用try-with-resources语法,JVM会自动帮你处理,不用手动写finally块。

内容的提问来源于stack exchange,提问作者Jose Lizarraga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:06:31