我正在尝试编写具有数据库连接性的BankingApp。现在,我正在努力更新用户的余额。用户输入他所存入的金额,然后从数据库中提取余额,并将其添加到数据库中,这至少是我的想法。
我将展示我的尝试。
编辑:我放置了第二个PreparedStatement并使用该语句执行了第二个查询,但是它仍然无法正常工作。
public void deposit(){
System.out.println("How much money do u want to deposit?");
int val = sc.nextInt();
try {
String query = "SELECT Balance FROM accounts.accs where AccountNumber =" + 654321 + "";
Connection con = DriverManager.getConnection(url,username,password);
PreparedStatement stmt = con.prepareStatement(query);
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
int balance = rs.getInt("Balance");
System.out.println("test");
int updatedBalance = balance+val;
System.out.println("the updatetbalance is" + updatedBalance +"");
String query2 = "UPDATE accs" +
"SET Balance = " + updatedBalance +"" +
"WHERE AccountNumber =" + 654321 +"";
PreparedStatement stmt2 = con.prepareStatement(query);
stmt2.executeUpdate(query2);
con.commit();
}
updatedBalance在控制台中显示正确,但在数据库中未更新。我在做什么错了?
答案 0 :(得分:1)
第一件事:请勿使用串联输入参数。容易发生SQL injection。
第二:您正在使用哪个DBMS?此更新可以使用 update-from-select 语句通过单个查询完成。语法因数据库而异,所以我不给它一个示例,但是您绝对应该考虑使用此选项。您可以在数据库文档中查找它。
最后,下面是使用两个PreparedStatement
应该对您有用的代码:
public void deposit() throws SQLException {
System.out.println("How much money do u want to deposit?");
int val = sc.nextInt();
int accountNumber = 654321;
String query = "SELECT Balance FROM accounts.accs where AccountNumber = ?";
try( Connection con = DriverManager.getConnection(url,username,password);
PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setInt(1, accountNumber);
ResultSet rs = stmt.executeQuery();
String query2 = "UPDATE accs " +
"SET Balance = ? " +
"WHERE AccountNumber = ?";
try (PreparedStatement stmt2 = con.prepareStatement(query2)) {
while (rs.next()){
int balance = rs.getInt("Balance");
System.out.println("test");
int updatedBalance = balance+val;
System.out.println("the updatetbalance is" + updatedBalance +"");
stmt2.setInt(1, updatedBalance);
stmt2.setInt(2, accountNumber);
stmt2.executeUpdate();
}
}
}
}