2014-01-12 22 views
1

我有这个错误。索引2超出范围。在pst.setString(2 textField.getText(); 我怎么能对付它SQL服务器索引超出范围错误

这是我的代码

try{ 
    String sql="update inventory set Name=?,Category=?,Brand=?,Price=?,ExDate=?,Tags=?,Quantity=?,Barcode=? where Id=?"; 
    pst.setString(2, textField.getText()); 
    pst.setString(3, textField_1.getText()); 
    pst.setString(4, textField_2.getText()); 
    pst.setString(5, textField_3.getText()); 
    pst.setString(6, textField_4.getText()); 
    pst.setString(7, textField_5.getText()); 
    pst.setString(8, textField_9.getText()); 
    pst.setString(9, textField_6.getText()); 
    pst.setString(1, textField_8.getText()); 
    pst=con.prepareStatement(sql); 
    pst.executeUpdate(); 

    JOptionPane.showMessageDialog(null,"Updating Item Successful","Updated",JOptionPane.PLAIN_MESSAGE); 

    new server().setVisible(true); 
    setVisible(false); 
} catch(Exception e1){e1.printStackTrace();} 
+3

为什么它的价值,我会移动pst = con.prepareStatement(sql);在我的String声明之后(String sql =“”),然后是setter方法。 – Ashish

+1

我不相信所有这些列都是真正的'varchar'列。为什么你们都使用'setString()'呢?你应该使用适当的'setXXX()'方法传递值(例如'setInt()'或'setDate()'),而不是让驱动程序隐式转换所有内容。 –

+0

@Ashish我只是解决了我的问题。 textField不在正确的位置。谢谢您的帮助。 – Rohan21

回答

1

基于documentation,夫妇的事情要注意这里。

您的sql包含名称 att索引1.因此,当您尝试更新此列时,应该使用相同的索引。像这样:

pst.setString(1, textField.getText()); 

你总是调用setString方法。虽然看起来像某些列可能是int或其他类型。例如你的“ID”栏应与此设置:

pst.setInt(9, Integer.parseInt(textField_8.getText())); (notice that I have changed the index as well.) 

正如我在我的评论前面提到的,你应该将你的pst=con.prepareStatement(sql)顶端。 (在你的字符串声明之后)。

+0

我已经尝试过,现在我有错误nvarchar值'3565547456644'的转换溢出了一个int列。 – Rohan21

+0

所以我们的想法是使用与列的数据类型相对应的特定setter方法。你可以查看这个链接,看看最适合你的情况。 http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html – Ashish

1

已准备语句应该被用来设置变量之前被创建。正如评论者说,你需要之前设置变量移动准备好的语句创建

重构代码是这样的:

try{ 
    String sql="update inventory set Name=?,Category=?,Brand=?,Price=?,ExDate=?,Tags=?,Quantity=?,Barcode=? where Id=?"; 
    pst=con.prepareStatement(sql); 
    pst.setString(2, textField.getText()); 
    pst.setString(3, textField_1.getText()); 
    pst.setString(4, textField_2.getText()); 
    pst.setString(5, textField_3.getText()); 
    pst.setString(6, textField_4.getText()); 
    pst.setString(7, textField_5.getText()); 
    pst.setString(8, textField_9.getText()); 
    pst.setString(9, textField_6.getText()); 
    pst.setString(1, textField_8.getText()); 

    pst.executeUpdate(); 

    JOptionPane.showMessageDialog(null,"Updating Item Successful","Updated",JOptionPane.PLAIN_MESSAGE); 

    new server().setVisible(true); 
    setVisible(false); 
} 
catch(Exception e1) 
{ 
    e1.printStackTrace(); 
} 
finally 
{ 
    pst.close(); 
}