2017-04-04 71 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

相關問題