他我是 Java 的菜鸟(这不是新的),我找不到一个好的教程。我使用 jTable 来显示一个填充了 MySQL 数据库数据的表。
到目前为止一切顺利,我得到了这张桌子:
标准,您可以单击表格单元格,它会更改为可以填充新内容的文本字段。你们都知道,但是我怎样才能使用它来更新我的数据库中的值呢?
我的代码:
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();
}
}
}
我想我需要绑定某种表侦听器,当发生变化时,我会获取表的所有值并使用查询更新它们。
我怎样才能做到这一点?
这是我的伪代码:
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]+";");
});