使用java swing表来更新MySQL数据库值

时间:2013-02-12 17:44:36

标签: java mysql swing jtable tablemodel

该程序用于从数据库中读取数据。在数据库中,有三个表pki17,pki18,pkn18。对于查看不同的表,使用JComboBox,它通过更改表的TableModel来工作。另外通过使用tableChanged方法我使表格可编辑。当表中的单元格值更改时,数据库中的相应值必须更改为。

当我一起使用tableChanged和actionPerformed方法时,当我在swing表中编辑单元格时,数据库中的值不会被更改。当我删除actionPerformed方法时,我可以通过编辑表格单元来更新数据库。

我需要两种能力,通过使用JComboBox从数据库中选择一个表,并通过编辑swing表中的值来更新数据库值。

我认为问题存在,因为表的TableModel在两种方法中都有所改变。但我不知道如何解决它。

public class TableCombobox extends JPanel implements ActionListener, TableModelListener  {
static JTable table;
static JComboBox box;
static MyTableModel model;
static Connection con = null;
static Statement stmt = null;

public TableCombobox() throws SQLException {
    super(new BorderLayout());
    table = new JTable(new MyTableModel("pki18"));
    table.setPreferredScrollableViewportSize(new Dimension(500, 400));
    table.setFillsViewportHeight(true);
    table.getModel().addTableModelListener(this);

    JScrollPane scrollPane = new JScrollPane(table);

    JPanel menuPanel = new JPanel();
    menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));
    menuPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1,
            Color.black));

    String[] dalykas = { "Chose groop", "pki17", "pki18", "pkn18" };
    box = new JComboBox(dalykas);
    box.setMaximumSize(new Dimension(150, 25));
    box.setAlignmentX(Component.LEFT_ALIGNMENT);
    box.addActionListener(this);
    box.setSelectedIndex(2);

    menuPanel.add(box);

    JPanel cards = new JPanel(new CardLayout());
    cards.add(scrollPane, "view");
    add(menuPanel, BorderLayout.LINE_START);
    add(cards, BorderLayout.CENTER);
}
public void tableChanged(TableModelEvent e) {
    int row = e.getFirstRow();
    int col = e.getColumn();
    model = (MyTableModel) e.getSource();
    String stulpPav = model.getColumnName(col);
    Object data = model.getValueAt(row, col);
    Object studId = model.getValueAt(row, 0);
    System.out.println("tableChanded works");
    try {
        new ImportData(stulpPav, data, studId);
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    } catch (SQLException e1) {
        e1.printStackTrace();
    }
}

public void actionPerformed(ActionEvent event) {        
        JComboBox cb = (JComboBox) event.getSource();
        String pav = (String) cb.getSelectedItem();
        if (pav != "Chose groop") {
            try {
                model = new MyTableModel(pav);
                table.setModel(model);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

private static void GUI() throws SQLException {
    JFrame frame = new JFrame("E-gradebook");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new TableCombobox());
    frame.pack();
    frame.setSize(800, 400);
    frame.setVisible(true);
}

public static void main(String[] args) throws SQLException {
    try {

        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/pki18",
                "root", "");
        GUI();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    } finally {
        if (stmt != null)
            stmt.close();
    }
}

static Connection getConnection() {
    return con;
}
}


public class ImportData {
static Connection con = TableCombobox.getConnection();

public ImportData(String a, Object b, Object c)
        throws ClassNotFoundException, SQLException {
    Statement stmt = null;
    try {

        String stulpPav = a;
        String duom = b.toString();
        String studId = c.toString();
        System.out.println(duom);
        con.setAutoCommit(false);
        stmt = con.createStatement();
        stmt.addBatch("update pki18 set " + stulpPav + " = " + duom
                + " where studento_id = " + studId + ";");
        stmt.executeBatch();
        con.commit();
    } catch (BatchUpdateException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (stmt != null)
            stmt.close();
        con.setAutoCommit(true);
        System.out.println("Data was imported to database");
    }
}   
}


public class MyTableModel extends AbstractTableModel{
static int rowCount;
static Object data [][];
static String columnNames [];

public  MyTableModel(String grupName) throws SQLException{
    String query ="select Studento_id, vardas_pavarde, 1_semestras,"+
            " 2_semestras, egzaminas, bendras_balas "+
            "from pki18." + grupName;

    ResultSet rs ;
    Connection con = TableCombobox.getConnection();

    Statement stmt = null;
    stmt = con.createStatement();
    rs = stmt.executeQuery(query);

    rs.last();
    rowCount = rs.getRow();
    data = new Object[rowCount][6];
    rs = stmt.executeQuery(query);
    for (int iEil = 0; iEil < rowCount; iEil++){
        rs.next();                  
        data[iEil][0] = rs.getLong("Studento_id");
        data[iEil][1] = rs.getString("Vardas_Pavarde");
        data[iEil][2]  = rs.getByte("1_semestras");
        data[iEil][3] = rs.getByte("2_semestras");
        data[iEil][4]  = rs.getByte("Egzaminas");
        data[iEil][5] = rs.getByte("bendras_balas");                    
    }

     String[] columnName  = {"Asmens_kodas","Vardas_Pavarde","1_Semestras"
            ,"2_Semestras","Egzaminas","Bendras_Balas"};
     columnNames = columnName;
}   
public int getColumnCount(){
    return columnNames.length;
}
public int getRowCount(){
    return data.length;
}
public String getColumnName(int col){
    return columnNames[col];
}
public Object getValueAt(int row, int col){
    return data[row][col];
}
public Class getColumnClass(int col){
    return getValueAt(0, col).getClass();
}
public boolean isCellEditable(int row, int col){
    return true;
}
public void setValueAt(Object value, int row, int col){
    data[row][col] = value;
    fireTableCellUpdated(row, col);
}
}

1 个答案:

答案 0 :(得分:1)

在构造函数中,只将表模型侦听器添加到当前模型:

table.getModel().addTableModelListener(this);

但是,在动作事件中,您将替换表模型:

model = new MyTableModel(pav);
table.setModel(model);

因此,新表模型将没有监听器,您将不再接收通知。让actionPerformed方法添加监听器,你的问题应该得到解决。