从JCombobox选择项目并删除数据库中的行 [英] Select item from JCombobox and delete the row in database

查看:52
本文介绍了从JCombobox选择项目并删除数据库中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,在这个项目中,我有一个SQLite数据库,其中包含一个名为Table1的表,其值的标题/位置没有作为列的ID,等等.

I am working on a project in which I have a SQLite database with a table called Table1 and values title/location without an ID as column etc...

我的表单有一个组合框,我设法使它在一行中的每个条目中显示我的数据库.现在,我想使用按钮删除"来删除我在组合框中选择的行,我有点迷失了.

My form has a combobox which I've managed to get it display my DB each entry in one row . Now I want with a button "Delete" to delete the row that I have selected in the combobox and I am kind of lost.

这是我的组合框代码(我认为很好):

Here is my code for the combobox (I think it's fine):

private void FillCombo(){
    try {
        String newLine = System.getProperty("line.separator");        
        Class.forName("org.sqlite.JDBC");
      connection = DriverManager.getConnection("jdbc:sqlite:C:\\users\\Kajou\\momentsdb.sqlite");
        statement = connection.createStatement();
        resultSet = statement.executeQuery("SELECT * FROM Table1");

        while (resultSet.next()) {    
            comboBox1.addItem(resultSet.getString("Title") + " " + "Date:" + resultSet.getString("Day")+"/"+ resultSet.getString("Month") +"/" + resultSet.getString("Year") + " " + resultSet.getString("Location")+ " " + resultSet.getString("Mood"));
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

现在有关按钮删除.我尝试了几件事,但看起来进展不佳:

And now about the button delete. I've tried few things but looks like not going well:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        Class.forName("org.sqlite.JDBC");                
        connection = DriverManager.getConnection("jdbc:sqlite:C:\\users\\Kajou\\momentsdb.sqlite");
        statement = connection.createStatement();
        String sql = "DELETE FROM Table1 WHERE col_string=Title";
        int deleteCount = statement.executeUpdate(sql);
        sql = "DELETE FROM Table1 WHERE col_string=?";
        pst = connection.prepareStatement(sql);
        pst.setString(1,"a string");
        deleteCount=pst.executeUpdate();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(DeleteImportantMomentsForm.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(DeleteImportantMomentsForm.class.getName()).log(Level.SEVERE, null, ex);
    }            
}

推荐答案

首先,对扩展名感到抱歉,但我为您提供了一些建议:)

First off, sorry for the extension but I have several advices for you :)

1)我的表单有一个组合框,我设法使其显示每个数据库 一行中输入

1) My form has a combobox which i managed to get it display my DB each entry in one row

这是将条目添加到组合框的方式:

Here is the way you're adding an entry to the combo box:

comboBox1.addItem(resultSet.getString("Title") + " " + "Date:" + 
                   resultSet.getString("Day")+"/"+ 
                   resultSet.getString("Month") +"/" + 
                   resultSet.getString("Year") + " " + 
                   resultSet.getString("Location")+ " " + 
                   resultSet.getString("Mood"));

这样,您将在组合框中添加一个非常大的字符串,这不是,但是如果将此信息映射到域类中,则可以大大改善.例如:

This way you'll get a very large string added to your combo box, which is not bad but can be highly improved if you map this info into a domain class. For instance:

class MyClass {
    int day, month, year;
    String title, location, mood;

    public MyClass(int day, int month, int year, 
                   String title, String location, String mood) {
        this.day = day;
        this.month = month;
        this.year = year,
        this.title = title;
        this.location = location;
        this.mood = mood;
    }

    // getters and setters are up to you :)
}

下一步是将新的MyClass对象添加到组合框中:

Next step is adding new MyClass objects to your combo box:

while (resultSet.next()) {
    MyClass myClass = new MyClass(resultSet.getInt("Day"),
                                  resultSet.getInt("Month"),
                                  resultSet.getInt("Year"),
                                  resultSet.getString("Title"),
                                  resultSet.getString("Location"),
                                  resultSet.getString("Mood"));
    comboBox1.addItem(myClass); // see note below
}

注意:必须在JComboBox) /dispatch.html"rel =" nofollow noreferrer>事件调度线程(又称EDT),它是一个特殊的线程.如果您在EDT中运行繁重的任务(例如数据库连接),则此任务可能会阻塞EDT,并且在完成此任务之前,您的GUI将冻结并且Swing组件将无法工作(甚至无法显示).为避免此问题,可以使用一些工具在单独的线程中执行繁重的任务并更新EDT中的Swing组件,例如 Swing中的并发.

Note: Swing components (such as JComboBox) must be created and updated in the Event Dispatching Thread (a.k.a. EDT) which is a single and special thread. If you have a heavy task running in the EDT (for instance database connections) then this task may block the EDT and your GUI will freeze and Swing components won't be able to work (or even display) untill this task is done. To avoid this issue there are some tools you can use to make the heavy tasks in a separate thread and update Swing components in the EDT, for instance SwingWorker. For further information take a look to Concurrency in Swing.

所以我建议您使用SwingWorker进行数据库调用:

So I would suggest you make database calls using a SwingWorker:

SwingWorker<Void,MyClass> worker = new SwingWorker<Void,MyClass>() {
    @Override
    protected Void doInBackground() throws Exception { // this take place in a background thread
        // connect to the database and execute the query here
        while (resultSet.next()) {
            MyClass myClass = new MyClass(resultSet.getInt("Day"), ...);
            publish(myClass);
        }
        return null;
    }

    @Override
    protected void process(List<MyClass> chunks){ // this take place in the EDT
        for(MyClass myClass : chunks){
            comboBox1.addItem(myClass);
        }
    }
}

现在,您已经将项目正确添加到了组合框中.下一步是使组合框根据需要显示文本.为此,您需要实现 ListCellRenderer .看一下提供自定义渲染器部分, 如何使用组合框教程.看看这个示例.关于将自定义渲染器设置为JList,但对JComboBox则完全相同.

Well now you have the items properly added to your combo box. Next step is make the combo box display the text as you wish. To do so you'll need to implement a ListCellRenderer. Take a look to Providing a Custom Renderer section in How to Use Combo Boxes tutorial. Take a look to this example. It's about setting a custom renderer to a JList but exactly the same applies to JComboBox.

2)现在,我想使用按钮删除"来删除我拥有的行 在组合框中选择,我有点迷路了

2) Now i want with a button "delete" to delete the row that i have selected in the combobox and i am kind of lost

请注意,您正在尝试执行两个不同的删除查询:

Please note you're trying to execute two different delete queries:

String sql = "DELETE FROM Table1 WHERE col_string=Title"; // This doesn't make sense
int deleteCount = statement.executeUpdate(sql); 
sql = "DELETE FROM Table1 WHERE col_string=?"; // This looks better I guess
pst = connection.prepareStatement(sql);

我怀疑其中一个查询(如果不是全部)都抛出异常.

I suspect one of these queries (if not both of them) throws an Exception.

由于您的组合框将包含MyClass个对象,因此您可以通过执行操作的方法进行此更改:

As your combo box will contain MyClass objects, you can make this change at the action performed method:

MyClass myClass = (MyClass)comboBox1.getSelectedItem();
String sql = "DELETE FROM Table1 WHERE Title = ?"; //If Title is the name of the column, of course
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1,myClass.getTitle());

注意:再次,在EDT中执行执行操作的方法.您应该将数据库调用移至后台线程,以避免阻塞EDT.

Note: Once again, the action performed method is executed in the EDT. You should move the database call to a background thread to avoid blocking the EDT.

这篇关于从JCombobox选择项目并删除数据库中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆