我是Java的新手,我正在尝试使用javafx gui从我创建的数据库中删除记录。我已经将数据库中的数据显示在tableView上并执行了删除行,但它只删除了tableView中的行而没有删除数据库中的记录。
如何在按下删除按钮时从数据库中删除记录?
以下是删除按钮的代码:
@FXML
private void kDELac( ActionEvent event ) throws SQLException {
allFiles = tableView.getItems();
fileSelected = tableView.getSelectionModel().getSelectedItems();
fileSelected.forEach( allFiles::remove );
DatabaseHandler handler = DatabaseHandler.getInstance();
handler.deleteRow(uniqueIdentifier);
}
...这里是负责从DB中删除的代码
private final String deleteQuery =
"DELETE FROM BOOK WHERE <UNIQUE_COLUMN> = ?";
public void deleteRow( String uniqueIdentifier ) {
Statement stmt = conn.createStatement();
stmt.executeUpdate( deleteQuery + uniqueIdentifier + "'" );
conn.commit();
}
负责从DB中删除的代码嵌入在DatabaseHandler.java类中:
public final class DatabaseHandler {
private static DatabaseHandler handler=null;
private static final String DB_URL = "jdbc:derby:database;create=true";
private static Connection conn = null;
private static Statement stmt = null;
private DatabaseHandler() {
createConnection();
setupBookTable();
}
public static DatabaseHandler getInstance() {
if( handler == null ) {
handler = new DatabaseHandler();
}
return handler;
}
void createConnection() {
class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
conn = DriverManager.getConnection(DB_URL);
}
void setupBookTable() {
String TABLE_NAME = "BOOK";
stmt = conn.createStatement();
DatabaseMetaData dbm = conn.getMetaData();
ResultSet tables =
dbm.getTables( null, null, TABLE_NAME.toUpperCase(), null );
if( tables.next()) {
System.out.println("Table " + TABLE_NAME + "already exists." );
}
else {
stmt.execute(
"CREATE TABLE " + TABLE_NAME + "("
+ " id varchar(200) primary key,\n"
+ " title varchar(200),\n"
+ " author varchar(200),\n"
+ " publisher varchar(100),\n"
+ " isAvail boolean default true"
+ " )");
}
}
public ResultSet execQuery(String query) {
ResultSet result;
stmt = conn.createStatement();
result = stmt.executeQuery(query);
return result;
}
public boolean execAction(String qu) {
stmt = conn.createStatement();
stmt.execute(qu);
return true;
}
private final String deleteQuery =
"DELETE FROM BOOK WHERE <UNIQUE_COLUMN> = ?";
public void deleteRow(String uniqueIdentifier) {
Statement stmt = conn.createStatement();
stmt.executeUpdate(deleteQuery + uniqueIdentifier + "'");
conn.commit();
}
}