java 使用 Netbeans 使用数据库刷新 jTable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6421778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Refreshing jTable with Database with Netbeans
提问by abc soeasy
I am developing a database application with Java and with MySQL as database. Am using Netbeans as a developing Tool.
我正在使用 Java 和 MySQL 作为数据库开发数据库应用程序。我使用 Netbeans 作为开发工具。
I need to display the stored database in a JTable.
我需要在 JTable 中显示存储的数据库。
Now when I add data to the database via query. The JTable is not showing the updated details instantly. I need to restart the application i.e. run it again.
现在,当我通过查询将数据添加到数据库时。JTable 不会立即显示更新的详细信息。我需要重新启动应用程序,即再次运行它。
Now I need to know how do I refresh the JTable when there is a change in DB.
现在我需要知道如何在 DB 发生变化时刷新 JTable。
Please provide me the steps or sample coding because I am not able to find a certain coding example on Internet.
请提供步骤或示例编码,因为我无法在 Internet 上找到某个编码示例。
回答by Hyman
Maybe it's enough to fire changes through the table model:
也许通过表模型触发更改就足够了:
yourTable.getModel().fireTableDataChanged()
回答by camickr
Whenever data in the database changes you need to recreate the TableModel and then update the table with the new model:
每当数据库中的数据发生更改时,您都需要重新创建 TableModel,然后使用新模型更新表:
TableModel model = ...
表模型模型 = ...
table.setModel( model );
回答by Ankur pandey
I faced the same problem, then i created the function named "UPDATEtable()" in which I put the connectivity code and called that function when it was needed to input data in Jtable from Mysql. For Refresh button , i first cleared the data from the table and then called the same function.
我遇到了同样的问题,然后我创建了一个名为“UPDATEtable()”的函数,我在其中放置了连接代码,并在需要从 Mysql 向 Jtable 中输入数据时调用了该函数。对于刷新按钮,我首先从表中清除数据,然后调用相同的函数。
Here is the code :-(Table Variable name - TB1)
这是代码:-(表变量名称 - TB1)
private void **UPDATEtable()**{
DefaultTableModel model=(DefaultTableModel) TB1.getModel();
try{
stmt= con.createStatement();
String query="SELECT * FROM goods ORDER BY order_num DESC;";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String PID = rs.getString("PID");
String Pname = rs.getString("Pname");
String NUM = rs.getString("order_num");
model.addRow(new Object[] {PID ,Pname,NUM);
}
}
catch(Exception e)
{
System.out.print(e);
}
FOR REFRESH BUTTON :-
对于刷新按钮:-
DefaultTableModel model=(DefaultTableModel) TB1.getModel();
while(model.getRowCount()>0){
model.setRowCount(0);
}
UPDATEtable();
回答by Ayvadia
You could also use the following code if you have instanciated tableNameList as observable:
如果您已将 tableNameList 实例化为 observable,您还可以使用以下代码:
tableNameList.clear();
tableNameList.addAll(tableQuery.getResultList());