MySQL DBからこのテーブルを読み込むためにJTableを作成し、MyTableModelを定義しました。しかし、問題は、UPDATE文を実行すると、JTableに追加の行が含まれていることです(ただし、MySQL DBには含まれません)。SQL UPDATE文を実行した後にJTableをリフレッシュする
アプリケーションを再オープンせずに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());
}
}
}
あなたがしていることは正確にはわかりませんが、データを保持しているVectorではなく、TableModelに直接更新する必要があります。 TableModelは適切なfireXXXメソッドを呼び出します。これらのメソッドを直接呼び出すべきではありません。 – camickr
私はQueryTableModelのコード全体を含めて私の投稿を編集しました。だから、setQueryUpdateはその一部です。 –