Jtable更新数据库mysql,JAVA更新数据库上的JTable单元格更改

He I am noob to Java (Thats not new) and I can't find a good tutorial for this. I use jTable to display a table filled with data from a MySQL database.

So far so good, I get the table:

bwPQa.png

Standard you can click a table cell and it changes to a text-field with can be filled with something new. You all know that, but how can I use this to also update the value in my database?

My code:

import [...];

public class table extends JPanel {

public String table;

private Database db;

public table(String tablename, Database db){

try {

table = tablename;

this.db = db;

//Get table with and height

ResultSet res = db.query("SELECT COUNT( * ) FROM `"+table+"`");

ResultSet res2 = db.query("SELECT COUNT( * ) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '"+table+"'");

int rows = 0;

int collums = 0;

res.next();

res2.next();

rows = res.getInt(1);

collums = res2.getInt(1);

//Get table column names and set then in array

ResultSet clom = db.query("DESCRIBE `"+table+"`");

String[] columnNames = new String[collums];

int s = 0;

while(clom.next()){

columnNames[s] = clom.getString(1);

s++;

}

//get table data and put in array

Object[][] data = new Object[rows][collums];

ResultSet result = db.query("SELECT * FROM `"+table+"`");

int q = 0;

while(result.next()){

for(int a=0; a<= (collums - 1); a++){

data[q][a] = result.getString(a + 1);

//System.out.println(q + " - " + a);

}

q++;

}

//Make Jtable of the db result form the two array's

final JTable table = new JTable(data, columnNames);

table.setPreferredScrollableViewportSize(new Dimension(500, 70));

table.setFillsViewportHeight(true);

// do some event listening for cell change

JScrollPane scrollPane = new JScrollPane(table);

JFrame frame = new JFrame("table editor");

scrollPane.setOpaque(true);

frame.setContentPane(scrollPane);

frame.pack();

frame.setSize(600, 800);

frame.setVisible(true);

} catch (SQLException e1) {

e1.printStackTrace();

}

}

}

I guess I need to bind some kind of table listener and when something changes I take all the values of the table and update them with a query.

How can I do this?

This is my pseudo code:

table.bindCellEventListner(callback(t){

Array row = t.getAllValuesAsArrayOfRow();

String data = "";

int f = 0

while(row.next()){

data .= "`"+clom[f]+"` = '"+row[f]+"',"

f++;

}

data.delLastChar();

db.query("UPDATE `"+table+"` SET "+data+" WHERE `id` ="+row[0]+";");

});

解决方案

A deleted answer plagiarised Rachel Swailes' answer from 14 years ago, found here. For completeness and because the answer is correct and useful, I have quoted the relevant text here:

Step 1: It's going to be way easier for the whole thing if you make your table extend a TableModel from now (if you haven't already). So if you need help with that just ask.

Step 2: In the table model you need to enable the cells to be editable. In the TableModel class that you make, you need to add these methods

public boolean isCellEditable(int row, int col) {

return true;

}

public void setValueAt(Object value, int row, int col) {

rowData[row][col] = value;

fireTableCellUpdated(row, col);

}

Step 3: You will see in the second method that we fire a method called fireTableCellUpdated. So here we can catch what the use it changing. You need to add a TableModelListener to your table to catch this.

mytable.getModel().addTableModelListener(yourClass);

And in the class that you decide will implement the TableModelListener you need this

public void tableChanged(TableModelEvent e) {

int row = e.getFirstRow();

int column = e.getColumn();

TableModel model = (TableModel)e.getSource();

Object data = model.getValueAt(row, column);

...

}

now you have the data in the cell and the place in the grid where the

cell is so you can use the data as you want

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了在Java Swing的JTable中显示MySQL数据库中的记录,你需要执行以下步骤: 1. 连接到MySQL数据库:使用JDBC API连接到MySQL数据库。你需要提供MySQL数据库的URL、用户名和密码。 2. 准备SQL查询:使用SQL查询语句从MySQL数据库中检索数据。 3. 执行SQL查询:执行SQL查询并将结果存储在ResultSet对象中。 4. 创建TableModel:TableModel是JTable显示数据的核心。你需要从ResultSet对象中检索列名和数据,并创建一个DefaultTableModel对象。 5. 创建JTable:使用DefaultTableModel对象创建JTable对象。 6. 添加JTable到JFrame:将JTable对象添加到JFrame中。 下面是一个示例代码,它演示了如何在Java Swing的JTable中显示MySQL数据库中的记录: ```java import java.sql.*; import javax.swing.*; import javax.swing.table.*; public class MySQLJTableExample extends JFrame { private JTable table; public MySQLJTableExample() { setTitle("MySQL JTable Example"); setSize(500, 500); setDefaultCloseOperation(EXIT_ON_CLOSE); // 连接到MySQL数据库 String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "mypassword"; String query = "SELECT * FROM mytable"; try (Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query)) { // 创建TableModel DefaultTableModel tableModel = new DefaultTableModel(); ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { tableModel.addColumn(metaData.getColumnName(i)); } while (resultSet.next()) { Object[] row = new Object[columnCount]; for (int i = 1; i <= columnCount; i++) { row[i - 1] = resultSet.getObject(i); } tableModel.addRow(row); } // 创建JTable table = new JTable(tableModel); // 添加JTable到JFrame add(new JScrollPane(table)); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { new MySQLJTableExample().setVisible(true); } } ``` 这个示例代码连接到名为"mydatabase"的MySQL数据库,用户名为"root",密码为"mypassword"。它从"mytable"表中检索所有记录,并在JTable中显示它们。你可以根据自己的需要修改代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值