3

我有java程序这样做:从数据库中获取数据并将它们附加到JTable中。

当我将数据添加到数据库中时,我无法刷新 JTable 以查看新数据,我应该关闭程序并再次运行它。

如何刷新/重新加载程序以查看数据

4

2 回答 2

2

好的,我会给你一个快速的解决方案:

package stack;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class Test {
    JTable table = new JTable();

    public void selectFrom(){
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        DefaultTableModel model=(DefaultTableModel)table.getModel();
        int rc= model.getRowCount();
        for(int i = 0;i<rc;i++){
            model.removeRow(0);
        }
        try{
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb","postgres","123");
            st = conn.createStatement();
            rs = st.executeQuery("select * from mytable");
            while(rs.next()){
                //Populate table
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void insertInto(){
        Connection conn = null;
        PreparedStatement pst = null;
            try{
                Class.forName("org.postgresql.Driver");
                conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb","postgres","123");
                pst = conn.prepareStatement("INSERT INTO mytable(id,first_column) VALUES(?,?)");
                //Insert into table using pst
                pst.execute();

                selectFrom();
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }
}
于 2012-09-01T01:17:39.353 回答
2

如果使用DefaultTableModel请参阅addRow方法。否则只需创建一个新模型并调用JTable.setModel(TableModel).

于 2012-09-01T01:26:24.927 回答