且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将表的所有数据放入JTable并将其插入到数据库中

更新时间:2023-02-10 12:58:04

First thing to do is to download the rs2xml.jar after installing this jar add it to your library. So you can populate your ResultSet to a TableModel. I made a sample gui using DB Derby where I can insert and populate it to table model. I used a Prepared Statement here.

private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {                                       
   String inputEmployee = employeeTf.getText();//textfields
   String inputDepartment = departmentTf.getText();//textfields

   if(inputEmployee.isEmpty() && inputDepartment.isEmpty()){
         JOptionPane.showMessageDialog(null, "Please fill up!");
    }//If blank
    else if(inputEmployee.isEmpty()){
        JOptionPane.showMessageDialog(null, "Employee Name should not be left blank");//If blank
    }
    else if(inputDepartment.isEmpty()){
        JOptionPane.showMessageDialog(null, "Department should not be left blank");//If blank
    }
    else{
        String myQuery = "INSERT INTO SAMPLE (EMPLOYEENAME,DEPARTMENT) VALUES (?,?)";

        try(Connection myCon = DBUtilities.getConnection(DBType.JDBC);//Establish the connection
        PreparedStatement myPs = myCon.prepareStatement(myQuery);
            ){

            myPs.setString(1, employeeTf.getText());
            myPs.setString(2, departmentTf.getText());

            myPs.executeUpdate(); // Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE;

            System.out.print("Record is inserted");

            DefaultTableModel model = (DefaultTableModel) Table_Employee.getModel();
            model.addRow(new Object[]{employeeTf.getText(),departmentTf.getText()});
        } catch (SQLException ex) {
            DBUtilities.processException(ex);
       }
    }//end of else
}

Syntax creating a table model:

DefaultTableModel model = (DefaultTableModel) Table_Employee.getModel();
            //yourTableModelName            //yourTableName
model.addRow(new Object[]{employeeTf.getText(),departmentTf.getText()});
                           //yourTextfield     //yourTextfield

Hope this helps. Link for rs2xml.jar http://en.osdn.jp/projects/sfnet_finalangelsanddemons/downloads/rs2xml.jar/