报错问题Parameter index out of range(0 < 1) (1 > number of parameters,which is 0

本文探讨了在使用JDBC连接数据库时,遇到的'Parameter index out of range'错误,主要集中在Db.Util工具类进行数据插入操作。错误通常由于占位符索引从1开始和缺少占位符导致。文章提到了两种插入数据的方法,并提醒开发者注意参数的正确设置。

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

jdbc连接数据库

public class DbUtil {
static{
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}
public static Connection getConnection(){
    String url = "jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8";
    String account = "root";
    String pwd = "root";
    Connection connection = null;
    try {
        connection = DriverManager.getConnection(url,account,pwd);
        } catch (SQLException e) {
        e.printStackTrace();
    }
    return connection;
}

使用Db.Util工具类插入数据的两种方法。

String sql = "insert into student(name,phone) values (?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1,firstname);
ps.setString(2,lastname);
ps.executeUpdate();

占位。setString表示第几个占位符。从1开始。

或者采用直接sql拼接。

String sql = "insert into student(name,phone) values('"+firstname+"','"+lastname+"')";
PreparedStatement ps = connection.prepareStatement(sql);
ps.executeUpdate();

setString可能会报的两个错误。

Parameter index out of range(0 < 1) 代表索引从1开始。

Parameter index out of range(1 > number of parameters,which is 0) 代表找不到占位符就是那个 ?号。

下面这个错记得加

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值