SQLException参数索引超出范围

时间:2014-04-22 00:13:05

标签: java sql exception jdbc

我在这段代码中做错了什么?它给出了一个SQLException,即参数超出范围,而我认为我已经给出了参数。

 try{
            String sql = "select item_type as 'Item Type', md_by as 'Made By',"
                    + " model as 'Model', selling_price as 'Selling Price', "
                    + "purchase_price as 'Purchase Price', "
                    + "purchase_date as 'Purchase Date', vouch_no as 'Voucher No.', "
                    + "vouch_date as 'Voucher Date', record_no as 'Record No.' "
                    + "from purchase where vouch_no = ?";
            ps.setInt(1, Integer.parseInt(txt_vouchno_p.getText()));
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            Table_p.setModel(DbUtils.resultSetToTableModel(rs));

        }   
        catch(SQLException ex){

                JOptionPane.showMessageDialog(null, "Error: " + ex);

        }
        catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Error: " + ex);
        }

1 个答案:

答案 0 :(得分:4)

您的调用方法顺序错误。首先,准备语句,然后设置绑定变量值。变化

ps.setInt(1, Integer.parseInt(txt_vouchno_p.getText()));
ps = con.prepareStatement(sql);

ps = con.prepareStatement(sql);
ps.setInt(1, Integer.parseInt(txt_vouchno_p.getText()));