【问题标题】:How to save edited JTable data to database?如何将编辑后的 ​​JTable 数据保存到数据库?
【发布时间】:2013-08-11 15:32:15
【问题描述】:

首先对我糟糕的英语感到抱歉。我会尽力理解你我的问题。

只要点击“保存”按钮,我只想保存用户在 JTable 中输入的新数据。

我正在从数据库的前两列中检索学生 ID、姓名,并且我在第三列中添加了当前日期,并且在第四列中添加了缺席/存在作为可编辑的第四列。我有以下代码从数据库中检索数据。

**Attendance.java** :
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package shreesai;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Vector;

/**
 *
 * @author Admin
 */

public class Attendance{

    Connection con = Connectdatabase.ConnecrDb();
    java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
    SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
    String d1 = fromUser.format(sqlDate);
    String d = d1.toString();
    public Vector getEmployee()throws Exception
    {

        Vector<Vector<String>> employeeVector = new Vector<Vector<String>>();

        PreparedStatement pre = con.prepareStatement("select studentid,name from student");
        ResultSet rs = pre.executeQuery();
        while(rs.next())
        {

            Vector<String> employee = new Vector<String>();
            employee.add(rs.getString(1)); //Empid
            employee.add(rs.getString(2));//name
            employee.add(d);
            employeeVector.add(employee);

        }        
        if(con!=null)
        con.close();
        rs.close();
        pre.close();

        return employeeVector;
    }

}

**AttendanceGUI.java : **

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package shreesai;

import static java.awt.Frame.MAXIMIZED_BOTH;
import java.sql.Connection;
import java.util.Vector;
import javax.swing.JOptionPane;

/**
 *
 * @author Admin
 */

public class AttendanceGUI extends javax.swing.JFrame {

    /**
     * Creates new form AttendanceGUI
     */
    Connection con = Connectdatabase.ConnecrDb();
    private Vector<Vector<String>> data;
    private Vector<String> header;
    public AttendanceGUI() throws Exception {

        this.setLocationRelativeTo(null);
        setExtendedState(MAXIMIZED_BOTH);
        Attendance att = new Attendance();

        data = att.getEmployee();

        header = new Vector<String>();
        header.add("Student ID");
        header.add("Student Name");
        header.add("Date");
        header.add("Absent/Present");
        initComponents();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        AttendanceT = new javax.swing.JTable();
        SaveAtt = new javax.swing.JButton();
        Exit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        AttendanceT.setModel(new javax.swing.table.DefaultTableModel(
            data,header
        )
        {public boolean isCellEditable(int row, int column){return true;}}

    );
    AttendanceT.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    TableColumnAdjuster tca = new TableColumnAdjuster(AttendanceT);
    tca.adjustColumns();
    AttendanceT.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    jScrollPane1.setViewportView(AttendanceT);

    SaveAtt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/save.png"))); // NOI18N
    SaveAtt.setText("Save Attendance");
    SaveAtt.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            SaveAttActionPerformed(evt);
        }
    });

    Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exit.png"))); // NOI18N
    Exit.setText("Exit");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(176, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
    }// </editor-fold>                        

    private void SaveAttActionPerformed(java.awt.event.ActionEvent evt) {                                        

    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try{
                    new AttendanceGUI().setVisible(true);
                }
                catch(Exception e){
                    JOptionPane.showMessageDialog(null,e);
                }
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JTable AttendanceT;
    private javax.swing.JButton Exit;
    private javax.swing.JButton SaveAtt;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration                   
}

我在运行 JFrame 时得到的输出:

现在,我真正想要的是每当用户将数据编辑到 JTable 中,就像下图一样:

****点击保存考勤按钮后,当前的 JTable 值应输入到数据库中。我正在使用 Firefox 中的插件 Sqlite 数据库。我在我的数据库中创建了出勤表,该表具有 studentid 整数、名称 varchar、日期 DATETIME 和 preab VARCHAR(用于存储特定学生是否存在)****

我希望你能明白我的问题所在。提前致谢。

【问题讨论】:

  • 请学习Java Naming Conventions并坚持下去,很难理解代码到底在做什么:(
  • 尽我最大的努力,对不起!
  • 不必感到抱歉,只是每种语言都有不同的约定,如果坚持使用它们,关于流程如何在运行时移动变得更容易理解通过代码:-) 毫无疑问,一个人从错误中学习 :-) 对于你提出这个问题的方式,我想对此表示赞同,但今天不能这样做,因为我的限制已经过去了 :(

标签: java sql swing jtable jframe


【解决方案1】:
     public void happi(String name, String age, String id){
//this method should be located on a class, then you just instantiate the class in the main form
String query=null;
try{

           query = "update tbltest set name = '"+name+"',age = '"+age+"' where id = '"+id+"'";
           stmt.executeUpdate(query);


       }
       catch(Exception ex){JOptionPane.showMessageDialog(null,""+ex);}
       finally{
           super.closeConnection(connect);
           super.closeStatement(stmt);

       }

}//end of happi

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    //a button with event ActionPerformed (save button)
   table.updateUI();

}//end

private void tablePropertyChange(java.beans.PropertyChangeEvent evt) {                                     
    // a JTablenamed"table"
    try{
    int row = table.getSelectedRow();
    int column = table.getSelectedColumn();
    int c = table.getColumnCount();

     DBHandler dbh = new DBHandler();
     dbh.happi((table.getModel().getValueAt(row, 0).toString()),     (table.getModel().getValueAt(row, 1).toString()), (table.getModel().getValueAt(row, 2).toString()));

    }catch(Exception e){}
} '

【讨论】:

  • 您可能需要添加更多描述以改进您的帖子。
  • 回复有点难以理解,描述也很少
【解决方案2】:

当您使用DefaultTableModel 时,您必须向该模型注册一个侦听器,TableModelListener 侦听更改。 How to use TableModelListener

例子:

myTable.getModel().addTableModelListener(new TableModelListener(){
         @Override
         public void tableChanged(TableModelEvent evt){
             //code here
         }
});

【讨论】:

  • 即使我使用的是 DefaultTableModel,我还是从 Attendance.java 文件中的向量中检索表数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
相关资源
最近更新 更多