如何在JTable上删除行并编辑任何已保存的数据并将其更新到mySQL数据库

时间:2013-10-06 08:01:04

标签: java sql swing jtable tablemodel

我正在制作一个注册系统,你可以通过JTextBox输入或删除任何学生信息。

到目前为止,我已允许我的程序添加数据。

我的问题是我正在尝试删除JTable中的行并反映我的SQL服务器中的更改。此外,我想允许我的程序编辑以前添加的任何数据。

我已经尝试了数小时的解决方案,但我仍然无法做到正确。

以下是源代码。

对于主要应用程序

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.table.*;
import javax.swing.event.*;

public class MalayaUniversityEnrollment extends JFrame implements ActionListener, ItemListener
{
JLabel header = new JLabel ("MALAYA UNIVERSITY ENROLLMENT SYSTEM");

JCheckBox jcb = new JCheckBox ("Enable Editing");

JLabel searchHeader = new JLabel ("SEARCH A STUDENT ");
JLabel infoHeader = new JLabel ("STUDENT INFORMATION");

JButton addButton = new JButton ("ENROLL STUDENT");
JButton editButton = new JButton ("EDIT/UPDATE INFO");
JButton deleteButton = new JButton ("DELETE STUDENT");
JButton searchButton = new JButton ("SEARCH IT!");
JButton clearButton = new JButton ("CLEAR ALL FIELDS");

JTextField studentIDField = new JTextField();
JTextField lastNameField = new JTextField();
JTextField firstNameField = new JTextField();
JTextField middleInitialField = new JTextField();
JTextField CYSField = new JTextField();
JTextField tuitionField = new JTextField();
JTextField statusField = new JTextField();
JTextField searchField = new JTextField();

JLabel studentIDLabel = new JLabel ("Student ID Number: ");
JLabel lastNameLabel = new JLabel ("Last Name: ");
JLabel firstNameLabel = new JLabel ("First Name: ");
JLabel middleInitialLabel = new JLabel ("Middle Initial: ");
JLabel CYSLabel = new JLabel ("CYS: ");
JLabel tuitionLabel = new JLabel ("Semestral Tuition: ");
JLabel statusLabel = new JLabel ("Status: ");
private final JTable table = new JTable()
{
    public boolean isCellEditable(int rowIndex, int colIndex) 
    {
        return false;   
    }
};
private final JScrollPane scrollPane = new JScrollPane();

String SID ="";
String lastName="";
String firstName="";
String middleInitial="";
String CYS="";
Double semestralTuition=0.00;
String studentStatus="";

String sid,lname,fname,midinit,cysection,stats;
Double semtui;



String sidPlacer,lnamePlacer,fnamePlacer,midinitPlacer,cysPlacer,statusPlacer;
Double tuitionPlacer;

String[] headers = {"Student ID", "Last Name", "First Name", "Middle Initial","CYS", "Semestral Tuition", "Status"};

DefaultTableModel model = new DefaultTableModel();

public MalayaUniversityEnrollment()
{
    super ("Malaya University [Enrollment]");

    Container c = getContentPane();
    c.setLayout(null);

    c.add(header);
    header.setBounds(290,20,1000,35);
    header.setFont(new Font("Tahoma", Font.PLAIN, 35));

    c.add(addButton);
    c.add(editButton);
    c.add(deleteButton);
    c.add(searchButton);
    c.add(clearButton);

    c.add(searchHeader);
    c.add(infoHeader);

    c.add(studentIDField);
    c.add(lastNameField);
    c.add(firstNameField);
    c.add(middleInitialField);
    c.add(CYSField);
    c.add(tuitionField);
    c.add(statusField);
    c.add(searchField);

    c.add(studentIDLabel);
    c.add(lastNameLabel);
    c.add(firstNameLabel);
    c.add(middleInitialLabel);
    c.add(CYSLabel);
    c.add(tuitionLabel);
    c.add(statusLabel);

    c.add(jcb);

    jcb.setBounds(565,766,146,23);

    studentIDLabel.setBounds(50,575,100,30);
    lastNameLabel.setBounds(50,615,100,30);
    firstNameLabel.setBounds(50,660,100,30);
    middleInitialLabel.setBounds(50,700,100,30);

    studentIDField.setBounds(175,575,200,30);
    lastNameField.setBounds(175,615,200,30);
    firstNameField.setBounds(175,660,200,30);
    middleInitialField.setBounds(175,700,200,30);

    CYSLabel.setBounds(450,575,100,30);
    tuitionLabel.setBounds(450,615,100,30);
    statusLabel.setBounds(450,660,100,30);

    CYSField.setBounds(575,575,200,30);
    tuitionField.setBounds(575,615,200,30);
    statusField.setBounds(575,660,200,30);

    infoHeader.setBounds(270,525,500,50);
    infoHeader.setFont(new Font("Tahoma", Font.PLAIN, 30));

    searchField.setBounds(885,638,300,30);
    searchHeader.setBounds(895,575,300,50);
    searchHeader.setFont(new Font("Tahoma", Font.PLAIN, 30));

    searchButton.setBounds(938,688,200,23);

    addButton.setBounds(450,700,146,23);
    editButton.setBounds(630,700,146,23);
    deleteButton.setBounds(450,733,146,23);
    clearButton.setBounds(630,733,146,23);

    studentIDField.setHorizontalAlignment(JTextField.CENTER);
    lastNameField.setHorizontalAlignment(JTextField.CENTER);
    firstNameField.setHorizontalAlignment(JTextField.CENTER);
    middleInitialField.setHorizontalAlignment(JTextField.CENTER);
    CYSField.setHorizontalAlignment(JTextField.CENTER);
    tuitionField.setHorizontalAlignment(JTextField.CENTER);
    statusField.setHorizontalAlignment(JTextField.CENTER);
    searchField.setHorizontalAlignment(JTextField.CENTER);


    scrollPane.setBounds(50, 88, 1190, 412);

    getContentPane().add(scrollPane);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setShowGrid(true);

    model.setColumnIdentifiers(headers);
    table.setModel(model);
    scrollPane.setViewportView(table);

    JTableHeader header = table.getTableHeader();

    header.setDefaultRenderer(new HeaderRenderer(table));

    table.getTableHeader().setReorderingAllowed(false);


    setSize(1300,850);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    for (int y=0; y<7; y++)
    {
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment( JLabel.CENTER );
        table.getColumnModel().getColumn(y).setCellRenderer( centerRenderer );
    }


    RetrieveData();

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() 
    {
    public void valueChanged(ListSelectionEvent e) 
        {
        int selectedRow = table.getSelectedRow();
        sid = (String)table.getValueAt(selectedRow, 0);
        lname = (String)table.getValueAt(selectedRow, 1);
        fname = (String)table.getValueAt(selectedRow, 2);
        midinit = (String)table.getValueAt(selectedRow, 3);
        cysection = (String)table.getValueAt(selectedRow, 4);
        semtui = (Double)table.getValueAt(selectedRow, 5);
        stats = (String)table.getValueAt(selectedRow, 6);
        studentIDField.setText(sid);
        lastNameField.setText(lname);
        firstNameField.setText(fname);
        middleInitialField.setText(midinit);
        CYSField.setText(cysection);
        tuitionField.setText(Double.toString(semtui));
        statusField.setText(stats);
        }
    });

    addButton.addActionListener(this);
    editButton.addActionListener(this);
    searchButton.addActionListener(this);
    deleteButton.addActionListener(this);
    clearButton.addActionListener(this);

    jcb.addItemListener(this);

    studentIDField.setEditable(false);
    lastNameField.setEditable(false);
    firstNameField.setEditable(false);
    middleInitialField.setEditable(false);
    CYSField.setEditable(false);
    tuitionField.setEditable(false);
    statusField.setEditable(false);

}

public void actionPerformed (ActionEvent aev)
{
    if (aev.getSource() == clearButton)
    {
        studentIDField.setText("");
        lastNameField.setText("");
        firstNameField.setText("");
        middleInitialField.setText("");
        CYSField.setText("");
        tuitionField.setText("");
        statusField.setText("");

    }

    if (aev.getSource() == deleteButton)
    {

        DataDeletion();


    }

    if (aev.getSource() == addButton)
    {
        String sidPlacer = studentIDField.getText();
        String lnamePlacer = lastNameField.getText();
        String fnamePlacer = firstNameField.getText();
        String midinitPlacer = middleInitialField.getText();
        String cysPlacer = CYSField.getText();
        Double tuitionPlacer = Double.parseDouble(tuitionField.getText());
        String statusPlacer = statusField.getText();

        try 
        {
            String queryAdd = "INSERT INTO `malaya university`.`2013-2014 enrollment` (`Student_ID`, `Last_Name`, `First_Name`, `Middle_Initial`, `CYS`, `Semestral_Tuition`, `Status`) VALUES (?,?,?,?,?,?,?)";
            DatabaseConfig a = new DatabaseConfig();
            a.ExecuteAddQuery(queryAdd , sidPlacer ,lnamePlacer,  fnamePlacer,  midinitPlacer,  cysPlacer,  tuitionPlacer, statusPlacer);


        }

        catch (Exception eee)
        {
            JOptionPane.showMessageDialog(null, "Record added Successfully.", "Registration Complete", JOptionPane.INFORMATION_MESSAGE);
            System.out.println(eee.getMessage());
        }

        model.addRow(new Object[]{sidPlacer,lnamePlacer,fnamePlacer,midinitPlacer,cysPlacer,tuitionPlacer,statusPlacer});
        studentIDField.setEditable(false);
        lastNameField.setEditable(false);
        firstNameField.setEditable(false);
        middleInitialField.setEditable(false);
        CYSField.setEditable(false);
        tuitionField.setEditable(false);
        statusField.setEditable(false);
        jcb.setSelected(false);

    }

    if (aev.getSource() == editButton)
    {
        String sidPlacer = studentIDField.getText();
        String lnamePlacer = lastNameField.getText();
        String fnamePlacer = firstNameField.getText();
        String midinitPlacer = middleInitialField.getText();
        String cysPlacer = CYSField.getText();
        Double tuitionPlacer = Double.parseDouble(tuitionField.getText());
        String statusPlacer = statusField.getText();

        try 
        {
            String queryEdit = "UPDATE  `malaya university`.`2013-2014 enrollment` SET `Student_ID` =  ? AND  `2013-2014 enrollment`.`Last_Name` =  ? AND  `2013-2014 enrollment`.`First_Name` =  ? AND  `2013-2014 enrollment`.`Middle_Initial` =  ? AND  `2013-2014 enrollment`.`CYS` =  ? AND CONCAT(`Semestral_Tuition` =  ? AND `2013-2014 enrollment`.`Status` =  ?)  WHERE  `2013-2014 enrollment`.`Student_ID` = '"+ sid + "' AND  `2013-2014 enrollment`.`Last_Name` =  '" + lname + "' AND  `2013-2014 enrollment`.`First_Name` =  '" + fname + "' AND  `2013-2014 enrollment`.`Middle_Initial` =  '" + midinit + "' AND  `2013-2014 enrollment`.`CYS` =  '" 
                    + cysection +  "' AND CONCAT( `2013-2014 enrollment`.`Semestral_Tuition` ) =  '" + Double.toString(semtui) + "' AND  `2013-2014 enrollment`.`Status` = '" + stats + "'";


            DatabaseConfig a = new DatabaseConfig();
            a.ExecuteEditQuery(queryEdit , sidPlacer ,lnamePlacer,  fnamePlacer,  midinitPlacer,  cysPlacer,  tuitionPlacer, statusPlacer,sid,lname,fname,midinit,cysection,semtui,stats);


        }

        catch (Exception eee)
        {
            JOptionPane.showMessageDialog(null, "Record updated Successfully.", "Update Complete", JOptionPane.INFORMATION_MESSAGE);
            System.out.println(eee.getMessage());
        }




        studentIDField.setEditable(false);
        lastNameField.setEditable(false);
        firstNameField.setEditable(false);
        middleInitialField.setEditable(false);
        CYSField.setEditable(false);
        tuitionField.setEditable(false);
        statusField.setEditable(false);
        jcb.setSelected(false);
    }
}

public void itemStateChanged(ItemEvent iev)
{
    if (iev.getSource() == jcb)
    {
        if(iev.getStateChange() == ItemEvent.SELECTED)
        {
            studentIDField.setEditable(true);
            lastNameField.setEditable(true);
            firstNameField.setEditable(true);
            middleInitialField.setEditable(true);
            CYSField.setEditable(true);
            tuitionField.setEditable(true);
            statusField.setEditable(true);
        }

        else
        {
            studentIDField.setEditable(false);
            lastNameField.setEditable(false);
            firstNameField.setEditable(false);
            middleInitialField.setEditable(false);
            CYSField.setEditable(false);
            tuitionField.setEditable(false);
            statusField.setEditable(false);
        }
    }
}

private static class HeaderRenderer implements TableCellRenderer 
    {

        DefaultTableCellRenderer renderer;

        public HeaderRenderer(JTable table) 
        {
            renderer = (DefaultTableCellRenderer)
            table.getTableHeader().getDefaultRenderer();
            renderer.setHorizontalAlignment(JLabel.CENTER);
        }


        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus, int row, int col) 

        {
            return renderer.getTableCellRendererComponent(
            table, value, isSelected, hasFocus, row, col);
        }
}

public void RetrieveData()
{
    try 
    {
        int x=0;
        String querySelect = "Select * FROM `2013-2014 enrollment`";
        DatabaseConfig a = new DatabaseConfig();
        ResultSet rs = a.showR(querySelect);

        while(rs.next())
        {
            SID = rs.getString("Student_ID");
            lastName = rs.getString("Last_Name");
            firstName = rs.getString("First_Name");
            middleInitial = rs.getString("Middle_Initial");
            CYS = rs.getString("CYS");
            semestralTuition = rs.getDouble("Semestral_Tuition");
            studentStatus = rs.getString("Status");

            model.addRow(new Object[]{SID,lastName,firstName,middleInitial,CYS,semestralTuition,studentStatus});
            x++;
        }



    } 
    catch (Exception e) 
    {
        JOptionPane.showMessageDialog(null, "There is Sum Thing Wong.", "ERROR", JOptionPane.ERROR_MESSAGE);
    }
}

public void DataDeletion()
{
    int r = model.getRowCount(); 
    for(int i=(r-1);i>=0;i--) 
    {
        model.removeRow(i); 
    }
}


public static void main (String[] args)
{
    try 
    {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }

    catch (Exception exe)
    {
        System.out.println("ERROR: Could not Load System UI.");
    }


    new MalayaUniversityEnrollment();   

}
}

这是保存SQL连接的类文件。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DatabaseConfig {

private String database = "jdbc:mysql://localhost:3306/malaya university";
private String user = "*";
private String password = "*";

Connection con;
Statement stmt = null;

public ResultSet showR(String q) throws Exception{
    try
    {
        Class.forName("com.mysql.jdbc.Driver");

        this.con = DriverManager.getConnection(this.database, this.user, this.password);
        PreparedStatement stmt = con.prepareStatement(q);

        ResultSet rs = stmt.executeQuery();

        return rs;

    } catch (SQLException e) {
        System.out.println(e.getMessage());
        return null;
    } finally {
        if (stmt != null) { stmt.close();}
    }

}
// execute for insert update delete

public void ExecuteAddQuery(String q,String sidPlacer, String lnamePlacer, String fnamePlacer, String midinitPlacer, String cysPlacer, Double tuitionPlacer, String statusPlacer)throws Exception{
    try{    
        Class.forName("com.mysql.jdbc.Driver");

        this.con = DriverManager.getConnection(this.database, this.user, this.password);

        PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO `malaya university`.`2013-2014 enrollment` VALUES (?,?,?,?,?,?,?)");

        //stmt = con.createStatement();

        pstmt1.setString(1,sidPlacer);
        pstmt1.setString(2,lnamePlacer);
        pstmt1.setString(3,fnamePlacer);
        pstmt1.setString(4,midinitPlacer);
        pstmt1.setString(5,cysPlacer);
        pstmt1.setDouble(6,tuitionPlacer);
        pstmt1.setString(7,statusPlacer);
        pstmt1.executeUpdate();

        stmt.executeUpdate(q);

    } catch (SQLException e) {

        System.out.println(e.getMessage());
    } finally {
        if (stmt != null) { stmt.close();}

    }
}

        public void ExecuteEditQuery(String q,String sidPlacer, String lnamePlacer, String fnamePlacer, String midinitPlacer, String cysPlacer, Double tuitionPlacer, String statusPlacer,String sid,String lname,String fname,String midinit,String cysection,Double semtui,String stats)throws Exception
        {
            try{    
                Class.forName("com.mysql.jdbc.Driver");

                this.con = DriverManager.getConnection(this.database, this.user, this.password);

                PreparedStatement pstmt2 = con.prepareStatement("UPDATE  `malaya university`.`2013-2014 enrollment` SET `Student_ID` =  ? AND  `2013-2014 enrollment`.`Last_Name` =  ? AND  `2013-2014 enrollment`.`First_Name` =  ? AND  `2013-2014 enrollment`.`Middle_Initial` =  ? AND  `2013-2014 enrollment`.`CYS` =  ? AND CONCAT(`Semestral_Tuition` =  ? AND `2013-2014 enrollment`.`Status` =  ?)  WHERE  `2013-2014 enrollment`.`Student_ID` = '"+ sid + "' AND  `2013-2014 enrollment`.`Last_Name` =  '" + lname + "' AND  `2013-2014 enrollment`.`First_Name` =  '" + fname + "' AND  `2013-2014 enrollment`.`Middle_Initial` =  '" + midinit + "' AND  `2013-2014 enrollment`.`CYS` =  '" 
                    + cysection +  "' AND CONCAT( `2013-2014 enrollment`.`Semestral_Tuition` ) =  '" + Double.toString(semtui) + "' AND  `2013-2014 enrollment`.`Status` = '" + stats + "'");



                pstmt2.setString(1,sidPlacer);
                pstmt2.setString(2,lnamePlacer);
                pstmt2.setString(3,fnamePlacer);
                pstmt2.setString(4,midinitPlacer);
                pstmt2.setString(5,cysPlacer);
                pstmt2.setDouble(6,tuitionPlacer);
                pstmt2.setString(7,statusPlacer);
                pstmt2.executeUpdate();

                stmt.executeUpdate(q);

    } catch (SQLException e) {

        System.out.println(e.getMessage());
    } finally {
        if (stmt != null) { stmt.close();}

    }

}

public void closeConnection() throws Exception
{
    this.con.close();
}



}

任何帮助将不胜感激。提前致谢。

编辑:点击删除学生按钮会出现此错误:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Vector.elementData(Vector.java:730)
at java.util.Vector.elementAt(Vector.java:473)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:649)
at javax.swing.JTable.getValueAt(JTable.java:2720)
at MalayaUniversityEnrollment$2.valueChanged(MalayaUniversityEnrollment.java:197)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:184)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:164)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:211)
at javax.swing.DefaultListSelectionModel.removeIndexInterval(DefaultListSelectionModel.java:677)
at javax.swing.JTable.tableRowsDeleted(JTable.java:4512)
at javax.swing.JTable.tableChanged(JTable.java:4415)
at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:296)
at javax.swing.table.AbstractTableModel.fireTableRowsDeleted(AbstractTableModel.java:261)
at javax.swing.table.DefaultTableModel.removeRow(DefaultTableModel.java:464)
at MalayaUniversityEnrollment.DataDeletion(MalayaUniversityEnrollment.java:419)
at MalayaUniversityEnrollment.actionPerformed(MalayaUniversityEnrollment.java:249)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:696)
at java.awt.EventQueue$4.run(EventQueue.java:694)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)

2 个答案:

答案 0 :(得分:0)

扩展DefaultTableModel并覆盖getValueAt()

class MyTableModel extends DefaultTableModel {
  public Object getValueAt(int r, int c) {
   if (r < 0 || c < 0) return "";
   return super.getValueAt(r, c);
  }
}

答案 1 :(得分:0)

以前在数据库使用中添加的数据:

select from table where rowid = last_insert_rowid()