问题描述
我在这里搜索找到错误的解决方案,但没有一个匹配我的问题,所以有人可以帮助我在我的代码中找到错误吗??
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());
}
} } );
注意:mysql声明它已在workbench中成功运行.谢谢
Note : mysql statement it's running successfully in workbench .thank you
推荐答案
删除问号占位符周围的单引号
Remove the single quotes around the question mark placeholder
更改此:
where item_name='?'
对此:
where item_name= ?
那应该可以解决问题.
使用单引号,prepareStatement将单引号视为包含字符串文字.字符串文字碰巧包含一个问号,但它没有将那个问号视为绑定占位符.
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.
因此,生成的准备好的语句只有一个占位符.这就是 setString
调用遇到错误的原因:没有第二个占位符可为其提供值.
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.
-
编辑
也从代码中删除此行:
st.executeUpdate(query);
并删除此行:
Statement st= conn.createStatement();
(代码正在创建并使用准备好的语句 ps
.)
(The code is creating and using a prepared statement ps
.)
这篇关于错误:参数索引超出范围(2>参数数量,即1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!