java - JTable(TableModel)与H2数据库连接的任何方式

标签 java sql swing h2 defaulttablemodel

我当前的项目是某种数据库系统,有一个用于维护的 GUI。在我重写主要代码之前,我曾经对TableModel进行序列化和反序列化。将数据保存和加载到 GUI。由于明显的原因,这不是一个好的解决方案,我做了一些研究,最终使用 H2 (本地)数据库来保存和加载我的数据。

The code used to save the data into my database can be found in my other question.

保存过程本身并不是最大的问题,但我找不到任何好方法将数据加载回我的 JTable (TableModel) .

有没有办法直接接线 JTable (TableModel)与任何类型的 SQL 数据库一起使用?目前,将 JTable 与数据库一起使用似乎对 Java 来说是一个很大的麻烦。

最佳答案

好的,这是一个简单的示例,它创建一个内存数据库,其中包含一个表和一些值。

它使用一个简单的自定义TableModel,如果底层数据发生更改,它可以“刷新”。

仔细看看JDBC Database Access了解更多详情

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class TestTable {

    private Connection con;

    public static void main(String[] args) {
        new TestTable();
    }

    public TestTable() {
        try {
            Class.forName("org.h2.Driver");
            String url = "jdbc:h2:mem:InMemoryTest";
            con = DriverManager.getConnection(url);

            createShoppingListTable();
            fillShoppingListTable();

            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        } catch (ClassNotFoundException | SQLException exp) {
            exp.printStackTrace();
        }
    }

    protected void createShoppingListTable() throws SQLException {
        String query = "create table shoppingList (id bigint identity, item varchar(255), quantity int)";
        try (Statement stmt = con.createStatement()) {
            stmt.execute(query);
        }
    }

    protected void fillShoppingListTable() throws SQLException {

        String[] items = {"Bananas", "Apples", "Grapes", "Pears", "Oranges"};
        Random rnd = new Random();
        try (PreparedStatement ps = con.prepareStatement("insert into shoppingList (item, quantity) values (?, ?)")) {
            for (String item : items) {
                ps.setString(1, item);
                ps.setInt(2, rnd.nextInt(100));
                ps.addBatch();
            }

            ps.executeBatch();
        }

    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());
            TestTableModel model = new TestTableModel();
            JTable table = new JTable(model);
            add(new JScrollPane(table));

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        model.refresh();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }

    }

    public class TestTableModel extends AbstractTableModel {

        private List<ShoppingList> shoppingList = new ArrayList<>(25);
        private List<String> columnNames = new ArrayList<>(25);

        @Override
        public int getRowCount() {
            return shoppingList.size();
        }

        @Override
        public int getColumnCount() {
            return columnNames.size();
        }

        @Override
        public String getColumnName(int column) {
            return columnNames.get(column);
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            ShoppingList rowValue = shoppingList.get(rowIndex);
            Object value = null;
            switch (columnIndex) {
                case 0:
                    value = rowValue.getId();
                    break;
                case 1:
                    value = rowValue.getItem();
                    break;
                case 2:
                    value = rowValue.getQuanity();
                    break;
            }
            return value;
        }

        public void refresh() throws SQLException {

            List<String> values = new ArrayList<>(25);
            try (PreparedStatement ps = con.prepareStatement("select * from shoppingList")) {
                try (ResultSet rs = ps.executeQuery()) {
                    ResultSetMetaData md = rs.getMetaData();
                    for (int col = 0; col < md.getColumnCount(); col++) {
                        values.add(md.getColumnName(col + 1));
                    }
                    while (rs.next()) {
                        ShoppingList list = new ShoppingList(rs.getLong(1), rs.getString(2), rs.getInt(3));
                        shoppingList.add(list);
                    }
                }
            } finally {
                if (columnNames.size() != values.size()) {
                    columnNames = values;
                    fireTableStructureChanged();
                } else {
                    fireTableDataChanged();
                }
            }

        }

        public class ShoppingList {

            private long id;
            private String item;
            private int quanity;

            public ShoppingList(long id, String item, int quanity) {
                this.id = id;
                this.item = item;
                this.quanity = quanity;
            }

            public long getId() {
                return id;
            }

            public String getItem() {
                return item;
            }

            public int getQuanity() {
                return quanity;
            }

        }

    }

}

关于java - JTable(TableModel)与H2数据库连接的任何方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32558578/

相关文章:

sql - 您如何对实体的自定义属性进行建模?

java - 多个组件的复杂布局

java - Liferay 工作流程与 Kaleo : use custom class on task

java - 为每条日志消息添加自定义值

java - 有没有 ListView 的下拉刷新功能的好例子?

Java套接字API : How to tell if a connection has been closed?

MySQL 语法 : bigger than value, 但不在 (...)

sql - 如何查找具有特定外键的所有表?

java - 在 JPanel 中显示多个 JTextField 和 JLabels 时遇到困难

java - 重新加载 JinternalFrame Java