【问题标题】:ERROR : Parameter index out of range (2 > number of parameters, which is 1)错误:参数索引超出范围(2 > 参数数量,即 1)
【发布时间】:2017-08-29 23:43:43
【问题描述】:

我在这里搜索以找到我的错误的解决方案,但没有人匹配我的问题,那么有没有人帮助我在我的代码中找到错误!?

 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语句在workbench中运行成功。 谢谢你

【问题讨论】:

    标签: java mysql sql eclipse interface


    【解决方案1】:

    去掉问号占位符周围的单引号

    改变这个:

      where item_name='?'
    

    到这里:

      where item_name= ?
    

    这应该可以解决问题。

    使用单引号,prepareStatement 将单引号视为包含 字符串文字。字符串文字恰好包含一个问号,但它没有将该问号视为绑定占位符。

    所以生成的预处理语句只有一个占位符。这就是setString 调用遇到错误的原因:没有第二个占位符可以为其提供值。

    --

    编辑

    同时从代码中删除这一行:

                st.executeUpdate(query);
    

    同时删除这一行:

                Statement st= conn.createStatement();
    

    (代码正在创建和使用准备好的语句ps。)

    【讨论】:

    • 非常感谢,我试过了,但有错误:{您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 '? 附近使用的正确语法。 FROM item_name=?'在第 1 行}
    • 看起来该错误来自 st.executeUpdate(query); 您不想要该行。删除它。该代码使用prepared statement (ps)。您根本不需要定义 st。删除 Statement st = 行。
    • true,谢谢你终于它的工作没有任何错误出现!但查询仍然没有在我的桌子上做任何事情。无论如何,非常感谢您的帮助。
    【解决方案2】:

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

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

    类型转换将自动处理..

    【讨论】:

    • 非常感谢,我试过了,但有错误:{您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 '? 附近使用的正确语法。 FROM item_name=?'在第 1 行}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    相关资源
    最近更新 更多