java 从数据库填充 JTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12127212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:41:32  来源:igfitidea点击:

Fill JTable from database

javasqldatabasejtabletype-2-dimension

提问by user1625324

I write this simple code to fill jTable1, but it just fills jTable1with 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);

}       

回答by user1625324

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

回答by Amarnath

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. So do like this,

是的,它始终是最后一行,因为在 while 循环中,您正在创建一个新的 JTable,而不是将一行附加到现有的 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});
}