简体   繁体   English

从数据库填充JTable

[英]Fill JTable from database

I write this simple code to fill jTable1 , but it just fills jTable1 with the last row from the database. 我写了这个简单的代码来填充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);

}       

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

Yes, it will always be the last row since in the while loop you are creating a new JTable instead of appending a row to the existing one. 是的,它将始终是最后一行,因为在while循环中,您正在创建一个新的JTable,而不是将一行附加到现有的JTable中。 So do like this, 所以这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM