2017-04-04 66 views
-1

我在这里搜索找到我的错误的解决方案,但没有人符合我的问题,有没有人帮我找到我的代码中的错误!?错误:参数索引超出范围(2>参数数量,这是1)

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

      } 

          } }); 

注意:mysql语句在工作台中成功运行。 谢谢

回答

0

周围的问号占位符

更改此删除单引号:

where item_name='?' 

要这样:

where item_name= ? 

应该可以解决这个问题。

使用单引号,prepareStatement将单引号看作包含字符串文字。字符串文字恰好包含问号,但不会将该问号视为绑定占位符。

因此,生成的准备语句只有一个占位符。这就是setString调用遇到错误的原因:没有第二个占位符为其提供值。

-

EDIT

此外删除此行从代码:

  st.executeUpdate(query); 

而且也删除该行:

  Statement st= conn.createStatement(); 

(该代码创建并使用准备好的声明ps。)

+0

太感谢你了,我是试过,但有错误:{您的SQL语法错误;检查与您的MySQL服务器版本相对应的手册,以便在''附近使用正确的语法'? FROM item where item_name =?'在第1行} – sara

+0

看起来这个错误来自**'st.executeUpdate(query);'**你不想要那一行。删除。代码使用*准备语句*(**'ps' **)。你根本不需要定义**'st' **。删除行**'Statement st ='**以及。 – spencer7593

+0

是真的,最后谢谢你的工作没有任何错误出现!但仍然查询不会在我的桌子上做任何事情。无论如何非常感谢您的帮助。 – sara

0

从第二个参数中删除引号。在引号内?被视为文字而不是作为参数。

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

类型转换将autonatically处理..

+0

非常感谢你,我尝试过,但有错误:{你的SQL语法错误;检查与您的MySQL服务器版本相对应的手册,以便在''附近使用正确的语法'? FROM item where item_name =?'在第1行} – sara

相关问题