简体   繁体   中英

SQLException Parameter index out of range

What am I doing wrong in this code? It gives a SQLException that a parameter is out of range while I think I have given the parameter.

 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);
        }

Your order of calling methods is wrong. First, you prepare the statement, then you set the bind variable values. Change

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM