Fill JTable from database

user1625324 picture user1625324 · Aug 26, 2012 · Viewed 14.3k times · Source

I write this simple code to fill jTable1, but it just fills jTable1 with the last row from the database.

String SQL = "select * from usernames";
ResultSet rs = stmt.executeQuery(SQL);
String[] columnNames = {"Full Name", "Email"}; 
String n = "",e = "";
while(rs.next()) { 
    n = rs.getString("Full_Name");
    e = rs.getString("Email");
    Object[][]data = {{n,e}}; 
    jTable1 = new JTable(data, columnNames);

}       

Answer

user1625324 picture user1625324 · Aug 27, 2012

I solved it by this code

String n = "",e = "";      

DefaultTableModel model;
model = new DefaultTableModel(); 
jTable1 = new  JTable(model);

model.addColumn("Full Name");
model.addColumn("Email");

while(rs.next())  
{
    n = rs.getString("Full_Name");    
    e= rs.getString("Email");   
    model.addRow(new Object[]{n,e});
}