索引1在java应用程序中超出范围错误

时间:2017-11-08 08:06:10

标签: java sql jdbc

当我运行此代码时:

String s = "insert into PersonalInfo(Name, FamilyName, FatherName, BirthDate, GenderID, NationalId) values";

PreparedStatement pst = con.prepareStatement(s);
pst.setString(1,Name.getText());    // error is at this line!
pst.setString(2,FamilyName.getText());
pst.setString(3,FatherName.getText());
pst.setString(4,BirthDate.getText());
if (Male.isSelected()){
    GenderID=1;
} 
if (Female.isSelected()){
    GenderID=2;
}
pst.setInt(GenderID,5);
pst.setString(6,NationalId.getText());
pst.executeUpdate();

我收到此错误:

  

索引1超出范围

但我不知道如何解决它。

2 个答案:

答案 0 :(得分:1)

您的查询没有占位符。将其更改为:

 String s = "insert into PersonalInfo (Name, FamilyName, FatherName, "
    + "BirthDate, GenderID, NationalId) values (?, ?, ?, ?, ?, ?)";

你也有一个错误:

pst.setInt(GenderID, 5);  // your code
pst.setInt(5, GenderID);  // correct code

答案 1 :(得分:0)

也许s的定义应该是

String s= "insert into PersonalInfo(Name, FamilyName, FatherName, BirthDate, GenderID, NationalId) values (?,?,?,?,?,?)"