如何使用JTable将更改的数据更新到数据库? [英] How to update changed data into the Database by using JTable?

查看:299
本文介绍了如何使用JTable将更改的数据更新到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello stackoverflow用户。



我想问几个问题。



从数据库获取数据并将其显示在JTable中。
另外,我想更新数据库中已在JTable中修改的数据,但我不知道如何做。我发现了一些例子,其他人做了,但他们不为我工作。



所以我的问题是这是如何获取和存储数据从数据库??
我目前使用数组字符串

  public String getDBUnits [] []; 

来存储和传递来自数据库的数据,并将数组转换为向量并显示数据a

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

我的JTable。



关于不同的方法,可以用来做,但我不知道哪一个是更好地对我的情况有用。



我会非常感激得到一些建议或教程。



感谢。



Ducky:)


$ b b p PS

解决方案

如果有人需要我从数据库获取数据的方法的代码,这是一个开放式的问题。



对我来说,你有几个选项...



...



在表中更改数据时,实时更新数据库。



要求您扩展 TableModel ,以便您可以访问 setValue 方法,这将允许您不仅更新模型的状态,但也更新数据库的状态(我会更新数据库,并成功时,更新模型,但是这是我)或附加一个监听器到模型并监控approriate TableChanged 事件并相应地更新数据库。



虽然这看起来像一个不错的方法,数据库已更新或与模型中的内容以及数据库中的内容不同步...



您可以...



创建一个表示数据库中数据的。当在此对象中更改值时,您只需提出一个标志,说明该行已更改。



当用户完成对表数据的更改时,会点击保存。然后,您将浏览所有对象,并确定哪些对象需要更新并将其保存回数据库。



这有可能允许陈旧数据要写回数据库(即用户A加载数据并开始进行更改,用户B在此期间加载数据,进行更改并将其保存回数据库,然后用户A保存更改,覆盖某些的用户B已经提交)



有两种方法可以解决,但您需要决定哪种方法最适合您当前的问题,实时或延迟更新...



更新了基本示例



do是通过创建一个表示数据库中的数据的类来开始的。通常,我从一个接口开始,并使用某种工厂生成实际的实现,但小步骤...



这有一个非常重要的变量, hasChanged 。这用于标记对象需要更新...

  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;
}
}
}

能够建模对象列表...

  public class PeopleTableModel extends AbstractTableModel {

private列表< Person>人;

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;
}
返回名称;
}

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

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

@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);
}
}
}

实现相同的东西,但基本上在这里我提供了 getChangedPeople 的方法,它将返回所有 People 改变。然后,您只需循环访问此列表并调用相应的数据库更新语句。


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 :)

P.S. 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.

这篇关于如何使用JTable将更改的数据更新到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆