Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.22/5 (2 votes)
See more:
Hi,
I am trying to insert new values in my database. but it keeps throwing a error "java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0)."
My code is:
Java
String sql;
           //String temp = jComboBox1.getSelectedItem();
           sql = "Insert into mytable (s_id,fname,lname,enrolled) values(?,?,?,?)";
           ps.setString(1,t_id.getText());
           ps.setString(2,t_fname.getText());
           ps.setString(3,t_lname.getText());
           ps.setString(4,(String) jComboBox1.getSelectedItem());

           ps = con.prepareStatement(sql);
           ps.execute();
           JOptionPane.showMessageDialog(null, "Record Inserted");

           update_table();
        }
        catch(SQLException er){
            System.out.println(er);
            JOptionPane.showMessageDialog(null,er);
        }


Please guide. I'm unable to locate the problem
Posted

See http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html[^]. You need to use the SQL statement to create ps before you add the parameters.
 
Share this answer
 
v2
Hi The below link might help you for sort out the issue.
http://stackoverflow.com/questions/2975797/exception-java-sql-sqlexception-parameter-index-out-of-range-1-number-of-par[^]

Please check whether the s_id is Primary key and auto increment or not.
If it is,then you don't need to give that data through insert query..


Try this..



Thanks
 
Share this answer
 
ps.setString(1,t_id.getText());
ps.setString(2,t_fname.getText());
ps.setString(3,t_lname.getText());
ps.setString(4,(String) jComboBox1.getSelectedItem());


--------------change to-----------------
ps.setString(0,t_id.getText());
ps.setString(1,t_fname.getText());
ps.setString(2,t_lname.getText());
ps.setString(3,(String) jComboBox1.getSelectedItem());

try
 
Share this answer
 
i thing s_ids PK no need to insert it
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900