java - java.sql.SQLExecption:更新sql的参数索引超出范围(1>参数个数,即0)
问题描述
我的项目有问题,使用 MYSQL 对我来说还是新的,我想从数据库中获取数据并进行一些计算并更新它的值,这就像像 ATM 机一样制作提款功能。这是我的桌子的样子。 在此处输入图像描述。您可以看到带有值的构造函数参数(字符串值和字符串 ID)。对于值 =“100”;和 ID="5221311" 你可以在我的桌子图片上看到它。
public ConformWithdraw() {
initComponents();
try {
Class.forName("com.jdbc.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:/atm", "root", "");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public ConformWithdraw(String value,String ID) {
initComponents();
this.value=value;
this.ID=ID;
}
------------------------------------------------------------
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
String validate = "SELECT * FROM customer_details WHERE accountID LIKE '" + ID
+ "'";
PreparedStatement smtm = con.prepareStatement(validate);
ResultSet resultSet = smtm.executeQuery();
User user = null;
if (resultSet.next()) {
user = new User();
user.setBalance(resultSet.getString("accountBalance"));
double balance=Double.parseDouble(user.getBalance());
double val=Double.parseDouble(value);
total =(balance - val);
}
smtm.close();
resultSet.close();
program();
} catch (SQLException | HeadlessException | ClassCastException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
-------------------------------------------------------------
public void program(){
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = '"+String.valueOf(total)+"'"
+ "WHERE accountID = '"+ID+"'";
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
PreparedStatement pstmt = con.prepareStatement(sqlUpdate);
id=Integer.parseInt(ID);
pstmt.setString(1, String.valueOf(total));
pstmt.setInt(2, id);
int rowAffected = pstmt.executeUpdate();
pstmt.close();
new ShowWithdraw().setVisible(true);
dispose();
}catch(SQLException | HeadlessException | ClassCastException ex){
JOptionPane.showMessageDialog(null, ex);
JOptionPane.showMessageDialog(null, "slh sini");
}
}
解决方案
您已经在查询中设置了参数,因此它尝试设置参数并且找不到要查找的参数。试试这个:
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = ?"
+ "WHERE accountID = ?";
推荐阅读
- python-2.7 - Python(2.7)使用套接字和选择模块进行多重聊天(非阻塞代码)
- c# - 从 Google Sheet API 中的模板复制,尽可能限制范围
- google-cloud-platform - Nifi 未写入 GCP Pub/Sub
- ssrs-2008-r2 - 2 个 Tablix 中的数据将在第 3 个中求和
- javascript - Jest 异常匹配类型和消息
- c# - 使用 signalR 核心客户端忽略 SSL 错误
- excel - Excel VBA - 确定模块是否包含在项目中
- c# - 如何在 dataGridView 中的 WindowsForm c# 中找到通过率?
- python - 在tkinter中忽略鼠标按钮事件?
- java - Android Studio:启动画面后应用程序崩溃