How to refresh jtable when database has changed
Hi everybody,
this is the first time I write here. I磎 not sure is this the right topic or not.
Anyway I have a problem with my code.
I have created jtable which displays mysql database and I have textfield where user inputs new data that goes to database by pressing button.
Problem is that new data goes to database
but ...jtable does not show it unless I close the program entirely and open it up again.
Here磗 a part of the code I磎 using. Any suggestions are appreciated.
package levyarkisto07;
import javax.swing.table.DefaultTableModel;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Connection;
class CTauluPohjaextends DefaultTableModel{
public CTauluPohja(){
try{
jbInit();
}
catch (Exception ex){
ex.printStackTrace();
}
}
private CTauluPohja model;
private Connection con;
publicvoid teeTaulu(ResultSet results){
try{
ResultSetMetaData metadata = results.getMetaData();
int columns = metadata.getColumnCount();
// Get the column names and set header names
for(int i = 0; i < columns; i++){
addColumn(metadata.getColumnLabel(i+1));
}
// Get all rows
while(results.next()){
String[] rowData =new String[columns];// Create array to hold the data
for(int i = 0; i < columns; i++){// For each column
rowData[ i ] = results.getString(i+1);// retrieve the data item
}
addRow(rowData);// Add a row
}
fireTableChanged(null);// Signal the table there is new model data
}catch (SQLException sqle){
System.err.println(sqle.getMessage());
}
}
privatevoid jbInit()throws Exception{
}
}
package levyarkisto07;
import java.sql.ResultSet;
import java.sql.*;
class CTietohaku{
private CTauluPohja model;
public CTietohaku(){
String url ="jdbc:mysql://localhost/levyarkisto";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url," "," ");
Statement stmt = con.createStatement();
String sql ="select tiedotid as ID, artistinimi as Artisti, levynimi as Levy, raitanro as Nro, kappalenimi as Kappale, levymuoto as T from levytiedot join levy using(levyid) join artisti using (artistiid) join raita using (raitaid) join kappale using (kappaleid) join levymuodot using (lmuotoid) order by artistinimi,levyid,raitaid";
ResultSet rs = stmt.executeQuery(sql);
haeTaulu(rs);
rs.close();
stmt.close();
con.close();
}
catch (Exception exc){
System.err.println(exc.getMessage());
}
try{
jbInit();
}
catch (Exception ex){
ex.printStackTrace();
}
}
public CTauluPohja getSanasto(){
return model;
}
void haeTaulu(ResultSet rs){
model =new CTauluPohja();// Create a table model
model.teeTaulu(rs);
}
privatevoid jbInit()throws Exception{
}
}
jTaTietokanta.setModel(hae.getSanasto());
Thank you

