1

i want to update my database using jtable, table r disply but not update please provide mi solution for it i am doing following code but it cant update my database and how can fire query for that my database contain id,name,password,email,phone_no

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.JFrame;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;


public class JtExample extends JFrame  {


JTable tbldetails;
     DefaultTableModel dtm ;
     public int editcol1;
     public int editrow;

      public JtExample() {
      setVisible(true);
      setSize(500,500);
      setTitle("login Frame");
      setLocationRelativeTo(null);
      setLayout(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      dtm = new DefaultTableModel();    //dtm consiste row and clonum
      String rowheader[] = {"ID","Name" ,"Password", "Email","phn_no"};
      dtm.addColumn("ID");
      dtm.addColumn("Name");
      dtm.addColumn("address");
      dtm.addColumn("Email");
      dtm.addColumn("phn_no");
      dtm.addRow(rowheader);
      add();


      dtm.addTableModelListener(new TableModelListener ()
      {

        @Override
        public void tableChanged(TableModelEvent arg0) {
              int  editcol1 =tbldetails.getEditingColumn();
              int editrow =tbldetails.getEditingRow();

              TableCellEditor tce = tbldetails.getCellEditor(editrow ,     editcol1);
              System.out.println(tce.getCellEditorValue());


        }

      });
      tbldetails = new JTable(dtm);

      tbldetails.setBounds(100,100,500,200);



      try {
        Class.forName("com.mysql.jdbc.Driver");
         Connection con = DriverManager.getConnection("jdbc:mysql://Localhost:3306/mydata","root","root");




            PreparedStatement ps=con.prepareStatement(" update employee set editcol1=? where editrow=?");
            int editcol1 = 0;
            String tce = null;
            ps.setString(editcol1, tce);

            int i=ps.executeUpdate();


    } catch (ClassNotFoundException e) {

        e.printStackTrace();
    } catch (SQLException e) {

        e.printStackTrace();
    }





      add(tbldetails); 


   }


   public void add()
   {

           try {
                Class.forName("com.mysql.jdbc.Driver");


                Connection con = DriverManager.getConnection("jdbc:mysql://Localhost:3306/mydata","root","root");


                Statement st = con.createStatement();




                ResultSet rs = st.executeQuery("select *from employee");
                while(rs.next())
                {
                    dtm.addRow(new Object[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5)});


                }


                con.close();

           } catch (ClassNotFoundException e) {

                e.printStackTrace();
            } catch (SQLException e) {

                e.printStackTrace();
            }   
       }








    public static void main(String args[])
    {
        new JtExample();

    }

}








    public static void main(String args[])
    {
        new JtExample();

    }

}
2
  • My first thought is, don't use a DefaultTableModel. Design a POJO which represents your data and use AsbtractTableModel instead... Commented Feb 18, 2015 at 3:05
  • Words typed in all lower case are hard to read, like trying to listen to someone who is mumbling. Please use an upper case letter at the start of sentences, for the word I, and proper names like ArrayList or Oracle. Commented Feb 18, 2015 at 3:43

1 Answer 1

1

Note: There is more then one way to skin this cat

My first thought is, don't use a DefaultTableModel, instead, use a AbstractTableModel, this will give you greater control of the model and changes to its state.

Start by defining a Plain Old Java Object (POJO) which represents your data. Personally I prefer to start with an interface, this allows me to define mutable and non-mutable versions depending on my requirements

Something like...

public class Employee {

    private String id; //??
    private String name;
    private String password; // Probably should be a char[]
    private String email;
    private String phoneNumber;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public Employee(String id, String name, String password, String email, String phoneNumber) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.email = email;
        this.phoneNumber = phoneNumber;
    }

}

...for example

Next, you need to define a TableModel which is capable of supporting this data...

public class EmployeeTableModel extends AbstractTableModel {

    private String columnNames[] = {"ID","Name" ,"Password", "Email","phn_no"};
    private List<Employee> employees;

    public EmployeeTableModel() {
        employees = new ArrayList<Employee>(25);
    }

    public EmployeeTableModel(List<Employee> employees) {
        this.employees = employees;
    }

    public void add(Employee employee) {
        employees.add(employee);
        fireTableRowsInserted(employees.size() - 1, employees.size() - 1);
    }

    public void remove(Employee employee) {
        int index = employees.indexOf(employee);
        employees.remove(employee);
        fireTableRowsDeleted(index, index);
    }

    @Override
    public int getRowCount() {
        return employees.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    public Employee getEmployeeAt(int row) {
        return employees.get(row);
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return String.class;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Employee emp = getEmployeeAt(rowIndex);
        Object value = null;
        switch (columnIndex) {
            case 0:
                value = emp.getId();
                break;
            case 1:
                value = emp.getName();
                break;
            case 2:
                value = emp.getPassword();
                break;
            case 3:
                value = emp.getEmail();
                break;
            case 4:
                value = emp.getPhoneNumber();
                break;
        }
        return value;
    }

}

We're going to add to this later, but for now, this gives us the basics we need...

When you load the data from the database, you could use something like...

EmployeeTableModel model = new EmployeeTableModel();
try (ResultSet rs = st.executeQuery("select *from employee")) {
    while(rs.next())
    {
        model.add(new Employee(
                rs.getString(1), 
                rs.getString(2), 
                rs.getString(3), 
                rs.getString(4), 
                rs.getString(5)));
    }
} finally {
    tbldetails.setModel(model);
}

So, now we have a self contained unit of work, in our Employee class, a TabelModel which can support it and a means by which you can load the data, now, you need some way to intercept the changes to the data and update the database.

To this end, we're going to update the EmployeeTableModel

public class EmployeeTableModel extends AbstractTableModel {
    //...
    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return columnIndex > 0; // id should not be editable here...
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        Employee emp = getEmployeeAt(rowIndex);
        switch (columnIndex) {
            case 1:
                emp.setName(aValue.toString());
                break;
            case 2:
                emp.setPassword(aValue.toString());
                break;
            case 3:
                emp.setEmail(aValue.toString());
                break;
            case 4:
                emp.setPhoneNumber(aValue.toString());
                break;
        }
        update(emp);
        fireTableCellUpdated(rowIndex, columnIndex);
    }

This will call the update method every time a cell is updated. To this, we pass the Employee object. Based on the value of the id property, you will either need to update or insert a new record.

This is a very simple example, because of the nature of JDBC, the JDBC call could take a period of time to execute. I might be tempted to have some kind of (blocking) queue, onto which I could add Employee objects.

This queue would be processed by another Thread (or SwingWorker or some such), which would pop off the next object and process it, triggering an event callback (to which the TableModel would be listening) with the updated data. The TableModel would then be able to update itself accordingly...

Another idea is to simply have a "save" button, which the user can click. You would then simply iterate through the list of Employees and update them. For this, I would have a simple boolean flag for each object, which would be set to true whenever any of the set methods are called

public class Employee {

    private boolean changed = false;

    public boolean hasChanged() {
        return changed;
    }

    public void setName(String name) {
        this.name = name;
        changed = true;
    }

Take a closer look at How to Use Tables for moe details

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.