[英]check if value (Accountnumber) exist in a java database
我在名為save的類中具有以下方法,正在使用JDBC數據庫保存和查看Java應用程序上的數據。
我的數據庫ZaiLab中有SAVINGS表,其中包含以下字段,
ID,ACCOUNTNUMBER,CUSTOMERNAME,BALANCE,MINMUM)
用戶將使用JOPtionPane輸入以下值。
(id,accountNumber,customername,balance,minmum);
然后,應用程序應檢查用戶輸入的accountNumber是否已經存在;如果不存在,則應將記錄保存到表SAVINGS中;如果是,則應顯示相應的消息。 “帳戶已經存在”。
public void openSavingsAccount(int Id, int Amount) {
try {
String host = "jdbc:derby://localhost:1527/ZaiLab";
String uname = "siduduzo";
String upass = "Password01";
Connection con = DriverManager.getConnection(host, uname, upass);
Statement stmt = con.createStatement();
String SQL = "SELECT * FROM SAVINGS";
ResultSet rs = stmt.executeQuery(SQL);
int minmum = 1000;
balance = minmum;
while (rs.next()) {
int acc_col = rs.getInt("ACCOUNTNUMBER");
if (acc_col == accountNumber) {
JOptionPane.showMessageDialog(null, "Sorry, account " + accountNumber
+ " aready Exist");
} else if (Amount < minmum) {
JOptionPane.showMessageDialog(null, "Can not Open the Account, Minimum amount to deposit must be R1000");
} else {
balance = balance + Amount;
id = Id;
stmt.executeUpdate("INSERT INTO `SAVINGS`(ID,ACCOUNTNUMBER,CUSTOMERNAME,BALANCE,MINMUM)VALUE ('" + id + "','" + accountNumber + "','" + customername + "'," + balance + ",'" + minmum + "')");
}
}
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
現在,您正在從SAVINGS
中選擇所有行,並嘗試為沒有“新”帳號的每一行插入一個新帳戶。
相反,您應該只選擇具有新帳號的行,並在不存在該行的情況下插入。
您還應該使用准備好的語句來防止SQL注入。
例如:
try (PreparedStatement checkAccountExists = con.prepareStatement(
"SELECT 1 FROM SAVINGS WHERE ACCOUNTNUMBER = ?")) {
checkAccountExists.setInt(1, accountNumber);
try (ResultSet rs = checkAccountExists.executeQuery()) {
if (rs.next()) {
// handle account already exists
} else {
try (PreparedStatement insert = con.prepareStatement(
"INSERT INTO SAVINGS(ID, ACCOUNTNUMBER, CUSTOMERNAME, BALANCE, MINMUM) VALUES (?, ?, ?, ? , ?)")) {
insert.setInt(1, id);
insert.setInt(2, accountNumber);
insert.setString(3, customername);
insert.setInt(4, balance);
insert.setInt(5, minmum);
insert.executeUpdate();
}
}
}
}
或者,您可以在數據庫中的ACCOUNTNUMBER
上定義唯一約束,然后執行插入操作,如果記錄已經存在,則處理約束違例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.