【发布时间】:2012-01-29 06:49:04
【问题描述】:
我创建了一个 JTable 并定义了 MyTableModel 以便从 MySQL DB 填充此表。但是,问题是当我执行 UPDATE 语句时,JTable 中包含了一个额外的行(但不在 MySQL DB 中)。
我应该如何更新我的代码才能在不重新打开应用程序的情况下正确更新 JTable? (我正在使用 fireTableChanged(null))
public class QueryTableModel extends AbstractTableModel {
Vector cache;
int colCount;
String[] headers;
String db;
String dbHost;
String dbLogin;
String dbPassw;
Statement statement;
public QueryTableModel() {
cache = new Vector();
}
public String getColumnName(int i) {
return headers[i];
}
public int getColumnCount() {
return colCount;
}
public int getRowCount() {
return cache.size();
}
public Object getValueAt(int row, int col) {
return ((String[]) cache.elementAt(row))[col];
}
public Connection getConnection()
throws Exception {
String dbURL = "";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Cannot find the MySQL JDBC driver. ");
throw (e);
}
try {
dbURL = "jdbc:mysql://" + dbHost + "/" + db;
// WINDOWS
Connection con = DriverManager.getConnection(dbURL,dbLogin,dbPassw);
// LINUX
// Connection con = DriverManager.getConnection(url);
return con;
} catch (SQLException e) {
System.out.println("No connection with " + dbURL);
throw (e);
}
}
public void setQuery(String query) {
cache = new Vector();
try {
// Execute the query and store the result set and its metadata
Connection con = getConnection();
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
colCount = meta.getColumnCount();
// Rebuild the headers array with the new column names
headers = new String[colCount];
for (int h = 1; h <= colCount; h++) {
headers[h - 1] = meta.getColumnName(h);
}
while (rs.next()) {
String[] record = new String[colCount];
for (int i = 0; i < colCount; i++) {
record[i] = rs.getString(i + 1);
}
cache.addElement(record);
}
fireTableChanged(null);
rs.close();
if (con.getAutoCommit() != false) {
con.close();
}
} catch (Exception e) {
cache = new Vector(); // blank it out and keep going.
e.printStackTrace();
}
}
public void setQueryUpdate(String[] data, String q) {
try {
Connection con = getConnection();
Statement statement = con.createStatement();
int rs = statement.executeUpdate(q);
String[] record = new String[data.length];
for (int i = 0; i < data.length; i++) {
record[i] = data[i];
}
cache.addElement(record);
fireTableChanged(null);
if (con.getAutoCommit() != false) {
con.close();
}
} catch (Exception e) {
cache = new Vector(); // blank it out and keep going.
System.out.println(e.getMessage());
}
}
}
【问题讨论】:
-
我不确定您在做什么,但应该直接对 TableModel 进行更新,而不是对保存数据的 Vector 进行更新。然后 TableModel 将调用正确的 fireXXX 方法。您不应该直接调用这些方法。
-
我刚刚编辑了我的帖子,包含了 QueryTableModel 的整个代码。所以,setQueryUpdate 只是其中的一部分。