Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

java - ERROR : Parameter index out of range (2 > number of parameters, which is 1)

i searched here to find solution for my error but no one match my problem , So is there anyone help me to find the error in my code !?

 textField_1.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {

            try{
            Object selected = list_1.getSelectedValue();
                Connection conn = null;
                conn=DriverManager.getConnection("jdbc:mysql://localhost/flyer","root","000");
                Statement st= conn.createStatement();

                String query = "INSERT INTO flyer_item (discount) SELECT price*? FROM `item` where item_name='?' ";

                // PreparedStatement ps = null;

                int i = Integer.valueOf((textField_1.getText()));
                i=i/100;
                java.sql.PreparedStatement ps = conn.prepareStatement(query);
                ps.setInt(1,i);
                ps.setString(2, selected.toString());
                ps.executeUpdate();
                st.executeUpdate(query);



            } catch (SQLException se){
                System.out.println(se.getMessage());

            }

                            } } );

Note : mysql statement it's running successfully in workbench . thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Remove the single quotes around the question mark placeholder

Change this:

  where item_name='?'

To this:

  where item_name= ?

That should resolve the problem.

With the single quotes, the prepareStatement is seeing the single quotes as enclosing a string literal. The string literal happens to contain a question mark, but it's not seeing that question mark as a bind placeholder.

So the resulting prepared statement only has a single placeholder. Which is why the setString call is encountering an error: there is no second placeholder to supply a value for.

--

EDIT

Also remove this line from the code:

            st.executeUpdate(query);

And also remove this line:

            Statement st= conn.createStatement();

(The code is creating and using a prepared statement ps.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...