[英]Remove objects from database through jList
I am building a Java GUI application in Netbeans intended to represent a digital till system (or ePOS till). 我正在Netbeans中构建一个Java GUI应用程序,用于表示数字耕作系统(或ePOS耕作)。
I need to be able to view a list of users through a jList, as well as modify and remove them. 我需要能够通过jList查看用户列表,以及对其进行修改和删除。 Each user is an object built with a User model class and represents a record on a mySQL accdb database. 每个用户都是使用User模型类构建的对象,并代表mySQL accdb数据库上的记录。
I have successfully managed to add users to the database, and populate the jList with the contents of an ArrayList containing User objects, but I don't understand how to remove the user I have selected in jList from the database. 我已经成功地将用户添加到数据库,并用包含User对象的ArrayList的内容填充了jList,但是我不知道如何从数据库中删除在jList中选择的用户。
The following is code to remove users from the db: 以下是从数据库中删除用户的代码:
// removes users from the database
public void removeUser (User dbUser) {
try (Connection conn = setupConnection()) {
// create SQL statement
Statement stmt = conn.createStatement();
// SQL query in string variable
String sql = "DELETE FROM Users " +
"WHERE employee_number = " +
dbUser.getEmployeeNumber();
// execute query on database
stmt.executeUpdate(sql);
} catch (Exception ex) {
String message = ex.getMessage();
System.out.println("dbUser error: " + message);
}
}
I understand this somewhat, but being able to target a specific user through jList and remove it from the database is something I cannot get my head around. 我对此有些了解,但是能够通过jList定位特定用户并将其从数据库中删除是我无法理解的事情。
I won't post my code for adding users and populating the jList unless asked, for the sake of clarity. 为了清楚起见,除非有要求,否则我不会发布用于添加用户和填充jList的代码。
Thank you. 谢谢。
I was able to solve my issue with this solution: 我可以使用以下解决方案解决问题:
This is the code: 这是代码:
// validate that an item is selected
if (user_lst.isSelectionEmpty()) {
JOptionPane.showMessageDialog(null, "You haven't selected an account to remove from the list.");
} else {
// target object at list index
int index = user_lst.getSelectedIndex();
// remove object at list index
model.getElementAt(index);
// create instance of user based on selected index
User u = (User) model.getElementAt(index);
if (index < 0) {
System.out.println("jList error: There are no items");
} else {
db.removeUser(u);
model.remove(index);
}
// refresh list model
user_lst.setModel(model);
// confirm user was removed
JOptionPane.showMessageDialog(null, "Account removed");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.