-1

我有这个数据库表:

create table users(
    id int not null auto_increment,
    fn varchar(30),
    ln varchar(30),
    sex char,
    email varchar(60),
    country varchar(40),
    username varchar(30),
    password varchar(100),
    primary key(id)
);

运行此代码时,出现错误:参数索引超出范围(8 > 参数数量,即 7)。我也尝试过改变setString(1,fn),但它不起作用。

 try{
     String INSERT="INSERT INTO users (fn,ln,,sex,email,country,username,password) VALUES (?,?,?,?,?,?,?)";
     PreparedStatement pst=conn.prepareStatement(INSERT);
     System.out.println("Created prepared statement");

     pst.setString(2,"fn");
     pst.setString(3,"ln");
     pst.setString(4,"sex");
     pst.setString(5,"email");
     pst.setString(6,"country");
     pst.setString(7,"username");
     pst.setString(8,"password)");
     pst.executeUpdate();
 }
4

4 回答 4

4

您的查询中有一个额外的逗号,并且您的列数应该从 1 开始。

String INSERT="INSERT INTO users (fn,ln,sex,email,country,username,password) VALUES (?,?,?,?,?,?,?)";
pst.setString(1,"fn");
    pst.setString(2,"ln");
    pst.setString(3,"sex");
    pst.setString(4,"email");
    pst.setString(5,"country");
    pst.setString(6,"username");
    pst.setString(7,"password)");
    pst.executeUpdate();
于 2013-07-23T09:37:04.563 回答
1

您正在传递 8 列和 7 个变量,计数不匹配。

确保这是:

String INSERT="INSERT INTO users (fn,ln,,sex,email,country,username,password) VALUES (?,?,?,?,?,?,?)";

应该是这样的:

String INSERT="INSERT INTO users (fn,ln,sex,email,country,username,password) VALUES (?,?,?,?,?,?,?)";
于 2013-07-23T09:36:50.553 回答
0

更正:

String INSERT="INSERT INTO users (fn,ln,sex,email,country,username,password) VALUES (?,?,?,?,?,?,?)";

short c = 0;
    //using a counter variable (short or int) means
    //no worries about numbering - just maintain the order below
pst.setString(++c,"fn");
pst.setString(++c,"ln");
pst.setString(++c,"sex");
pst.setString(++c,"email");
pst.setString(++c,"country");
pst.setString(++c,"username");
pst.setString(++c,"password)");

注:++c是前置自增运算符。它将c(设置c为此)的当前值加 1 并使用 的新值c

于 2013-07-23T09:49:22.307 回答
0

相对于查询的参数编号

pst.setString(1,"fn");
pst.setString(2,"ln");
pst.setString(3,"sex");
pst.setString(4,"email");
pst.setString(5,"country");
pst.setString(6,"username");
pst.setString(7,"password)");
pst.executeUpdate();
于 2013-07-23T09:43:41.737 回答