简体   繁体   中英

How to update changed data into the Database by using JTable?

Hello stackoverflow users.

I would like to ask couple of questions.

I currently able to get the data from the Database and display it in JTable. In addtion, I would like to update the data in the Database that has been modified in the JTable but I don't know how to do it. I found some of the examples what other people did but they did not work for me.

So my question is this: Does it matter how you getting and storing data from the Database?? I currently using Array of String

public String getDBUnits  [][]; 

to store and pass data from the Database and converting the Array in to the Vector and display the data using a

table.setModel(new DefaultTableModel(getDBGrades,gradeHeader));

for my JTable.

I know about different methods that can be used to do it but I don't know which is one is better be useful for my situation.

I will be highly appreciated to get some advice or tutorial.

Thanks.

Ducky :)

PS If any one need a code of the methods I use to get data from the Database I will be happily to post them.

This is an open ended question.

For me, you have a few options...

You Could...

Update the database in real time as the data is changed within the table.

This would require you to either extend the TableModel so you have access to the setValue method, which would allow you to not only update the state of the model, but also update the state of the database (I'd update the database and when successful, update the model, but that's me) OR attach a listener to the model and monitor for approriate TableChanged events and update the database accordingly.

While this looks like a nice method, you run the risk of "hanging" the UI while the database is been updated or getting out of sync with what's in the model and what's in the database...

You Could...

Create an Class that represents the data from the database. When a value is changed within this object, you would simply raise a flag stating that the row has changed.

When the user has finished making changes to the table data, they would click "save". You would then walk through all the objects and determine which ones need to be updated and "save" them back to the database.

This does have the potential to allow "stale" data to be written back to the database (ie User A loads the data and starts making changes. User B in the meantime loads the data, makes a changes and saves it back to the database. User A then saves their changes, overwriting some of the changes User B has already committed)

There are approaches to solving both, but you need to decide on which approach you best suits your current problem, real-time or delayed updates...

Updated with basic example

The first thing to do is start by creating a class that represents the data from your database. Normally, I'd start with a Interface and use some kind of factory to generate the actual implementation, but small steps...

This has one very important variable, hasChanged . This is used to flag the object has needing to be update...

public class Person {

    private boolean hasChanged = false;

    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public boolean hasChanged() {
        return hasChanged;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setFirstName(String value) {
        if (value == null ? firstName != null : !value.equals(firstName)) {
            firstName = value;
            hasChanged = true;
        }
    }

    public void setLastName(String value) {
        if (value == null ? lastName != null : !value.equals(lastName)) {
            lastName = value;
            hasChanged = true;
        }
    }
}

Next we built a table model capable of modeling a list of of objects...

public class PeopleTableModel extends AbstractTableModel {

    private List<Person> people;

    public PeopleTableModel() {
        people = new ArrayList<>(20);
    }

    public void addPerson(Person person) {
        people.add(person);
        fireTableRowsInserted(people.size() - 1, people.size() - 1);
    }

    public Person getPersonAt(int row) {
        return people.get(row);
    }

    public List<Person> getChangedPeople() {
        List<Person> changed = new ArrayList<>(people.size());

        for (Person p : people) {
            if (p.hasChanged()) {
                changed.add(p);
            }
        }

        return changed;    
    }

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

    @Override
    public String getColumnName(int column) {
        String name = null;
        switch (column) {
            case 0:
                name = "First name";
                break;
            case 1:
                name = "First name";
                break;
        }
        return name;
    }

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Person p = people.get(rowIndex);
        Object value = null;
        switch (columnIndex) {
            case 0:
                value = p.getFirstName();
                break;
            case 1:
                value = p.getLastName();
                break;
        }
        return value;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        if (aValue instanceof String) {
            Person p = people.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    p.setFirstName(aValue.toString());
                    break;
                case 1:
                    p.setLastName(aValue.toString());
                    break;
            }
            fireTableRowsUpdated(rowIndex, rowIndex);
        }
    }
}

There are any number of ways to achieve the same thing, but basically here I've provided method called getChangedPeople which will return all the People that have changed. You would then simply loop through this list and call the appropriate database update statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM