通过 JavaFX GUI 从数据库中删除数据

Deleting Data From Database Through JavaFX GUI

我想要做的是通过 table 查看 select 一个项目加载我的数据库并将其删除到数据库中。我没有让用户输入特定歌曲的 ID,因此这让我更难完成此操作。我已经设置了 GUI 以及我目前拥有的所有代码。

GUI 代码:

歌曲内容代码:

  /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package playmymusic;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

/**
 *
 * @author man
 */
public class SongContent 
{
    private final StringProperty artist;
    private final StringProperty title;
    private final StringProperty genre;
    private final IntegerProperty id;

   public SongContent(int id, String artist, String title, String genre)
   {
       this.artist = new SimpleStringProperty(artist);
       this.title = new SimpleStringProperty(title);
       this.genre = new SimpleStringProperty(genre);
       this.id = new SimpleIntegerProperty(id);
   }

   public Integer getId()
   {
       return id.get();
   }
   public void setID(int paramId)
   {
       id.set(paramId);
   }

   public String getArtist()
   {
       return artist.get();
   }
   public void setArtist(String paramArtist)
   {
       artist.set(paramArtist);
   }

   public String getTitle()
   {
       return title.get();
   }
   public void setTitle(String paramTitle)
   {
       title.set(paramTitle);
   }

   public String getGenre()
   {
       return genre.get();
   }
   public void setGenre(String paramGenre)
   {
       genre.set(paramGenre);
   }

   public StringProperty artistProperty(){return artist;}
   public StringProperty titleProperty(){return title;}
   public StringProperty genreProperty(){return genre;}
   public IntegerProperty idProperty() { return id;}
}

控制器代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package playmymusic;

import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.beans.property.IntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
import org.apache.derby.jdbc.ClientDriver;
/**
 *
 * @author man
 */
public class FXMLDocumentController implements Initializable {
    public LoginModel loginModel = new LoginModel();

    @FXML
    private TextField txtUsername;
    @FXML
    private TextField txtPassword;

    @FXML
    private TextField txtArtist;
    @FXML
    private TextField fxTitle;
    @FXML 
    private TextField fxGenre;

    @FXML
    private TableView<SongContent> tableView;

    @FXML
    private TableColumn<SongContent, Integer> id;

    @FXML
    private TableColumn<SongContent, String> artist;
    @FXML
    private TableColumn<SongContent, String> title;
    @FXML
    private TableColumn<SongContent, String> genre;

    private ObservableList<SongContent> data;


    @FXML
    private void Login(ActionEvent event) throws SQLException {
        try {
            if(loginModel.isLogin(txtUsername.getText(), txtPassword.getText()))
            {
                Stage primaryStage = new Stage();
                                FXMLLoader loader = new FXMLLoader();
                Pane root = loader.load(getClass().getResource("PopUpWindow.fxml").openStream());

                Scene scene = new Scene(root, 785, 809);
                primaryStage.setScene(scene);
                primaryStage.show();

                PlayMyMusic.primaryStage.close();
            }else 
            {
                            System.out.println("WOOPS");
                        }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
                }
    }


    @FXML
    private void songs(ActionEvent e) throws SQLException, ClassNotFoundException 
    {

        loginModel.insertSongs(txtArtist.getText(), fxTitle.getText(), fxGenre.getText());    
        try
        {
            int i = 1;
            Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/PlayMyMusicDB;user=test;password=test");
            data = FXCollections.observableArrayList();

            ResultSet rs = conn.createStatement().executeQuery("select * from Song");
            while(rs.next())
            {
                data.add(new SongContent(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)));
                i++;
            }
        }catch(SQLException ex)       {
            System.err.println("Error"  + ex);
        }
        id.setCellValueFactory(new PropertyValueFactory<>("id"));
        artist.setCellValueFactory(new PropertyValueFactory<>("artist"));
        title.setCellValueFactory(new PropertyValueFactory<>("title"));
        genre.setCellValueFactory(new PropertyValueFactory<>("genre"));

        tableView.setItems(null);
        tableView.setItems(data);
        txtArtist.clear();
        fxTitle.clear();
        fxGenre.clear();

    }

    @FXML
    public void deleteItems(ActionEvent e) throws SQLException, ClassNotFoundException
    {
        Connection c = DriverManager.getConnection("jdbc:derby://localhost:1527/PlayMyMusicDB;user=test;password=test");
        int action = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this item?");
        if(action == 0)
        {
            try
            {
               IntegerProperty i = SongContent.idProperty();

               ResultSet rs = c.createStatement().executeQuery("DELETE FROM Song where i = " + i);


            }catch(Exception e1)
            {
                e1.printStackTrace();
            }
        }
    }


    @Override
    public void initialize(URL url, ResourceBundle rb)
    {

    }    
}
`

任何关于为什么这不能删除我的数据的解释?如果有人向我解释每次 GUI 打开和关闭时重置 SongNumberID 的策略,我也会很高兴。但是,我的主要目标是弄清楚如何删除歌曲。

非常感谢 -亚伦

SimpleIntegerProperty 上调用 toString 的结果类似于 IntegerProperty [value: 10]。您应该使用值,而不是 IntegerProperty。此外,最好使用 PreparedStatement 来创建查询。此外,您应该从 table 中获取所选项目,而不是像 static:

那样尝试引用实例方法
SongContent song = tableView.getSelectionModel().getSelectedItem();
if (song != null) {
    // there is a selection -> delete
    ...

    PreparedStatement statement = c.prepareStatement("DELETE FROM Song WHERE i = ?");
    statement.setInt(1, song.getId());
    statement.executeUpdate();
    ...
}

此外,您应该确保 i 实际上是 id 列的列名(而不是 id)。