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

时间:2016-10-29 02:14:05

标签: jdbc netbeans javafx fxml

我想要做的是通过表视图加载我的数据库选择一个项目并将其删除到数据库中。我没有用户输入特定歌曲的ID,所以这使我更难实现这一点。我有GUI设置和我到目前为止的所有代码。

GUI代码:enter image description here

SongContent Code:

  /*
 * 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的策略,我也会喜欢它。但是,我的主要目标是找出如何删除歌曲。

非常感谢 -Aaron

1 个答案:

答案 0 :(得分:1)

toString上调用SimpleIntegerProperty的结果类似于IntegerProperty [value: 10]。您应该使用该值,而不是IntegerProperty。此外,最好使用PreparedStatement来创建查询。此外,您应该从表中获取所选项目,而不是尝试引用实例方法,就像它是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)。