从数据库填充JTable

时间:2012-08-26 02:35:18

标签: java sql database jtable type-2-dimension

我编写这个简单的代码来填充jTable1,但它只是用数据库的最后一行填充jTable1

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);

}       

2 个答案:

答案 0 :(得分:3)

我用这段代码解决了它

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});
}

答案 1 :(得分:2)

是的,它始终是最后一行,因为在while循环中,您正在创建一个新的JTable而不是向现有的一行添加一行。所以这样做,

// Code
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
while(rs.next())
{ 
    n = rs.getString("Full_Name");
    e= rs.getString("Email");
    //Object[][]data={{n,e}};
    // This will add row from the DB as the last row in the JTable. 
    model.insertRow(jtable1.getRowCount(), new Object[] {n, e});
}