SQL数据和JTable

问题描述 投票:-3回答:2

我正在尝试一个示例程序进行练习,我想在JTable中显示数据库的结果。问题是我不知道该怎么做。我知道如何从数据库中获取数据并将其显示在文本字段或控制台上,但从未尝试使用JTable。怎么做 ?

考虑一下,我的表格中包含了人名,年龄,城市和日期等信息。我希望它通过JTable显示。如果我添加在程序中添加更多细节的选项(我的意思是在db中添加条目然后将立即显示在JTable中),也可以更新JTable显示吗?

任何建议,关于如何进行的指示表示赞赏。提前致谢。

java sql swing
2个回答

0
投票

这是代码

public static TableModel resultSetToTableModel(ResultSet rs) {
try {
    ResultSetMetaData metaData = rs.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    Vector<String> columnNames = new Vector<String>();

    // Get the column names
    for (int column = 0; column < numberOfColumns; column++) {


    columnNames.addElement(metaData.getColumnLabel(column + 1).toUpperCase());
    }

    // Get all rows.
    Vector<Vector<Object>> rows = new Vector<Vector<Object>>();

    while (rs.next()) {
    Vector<Object> newRow = new Vector<Object>();

    for (int i = 1; i <= numberOfColumns; i++) {
        newRow.addElement(rs.getObject(i));
    }

    rows.addElement(newRow);
    }

    return new DefaultTableModel(rows, columnNames);
} 
catch (Exception e)
{
    e.printStackTrace();

    return null;
}

}

你可以这样调用这种方法

void update_Table() throws ParseException 
    {
        // we used this try catch so that values in table  automatically show(without clicking on any button) when the dialog box open          
                    try
                    {
                   Connection con=MSUTIL.getMSConnection();
                    PreparedStatement  pst=con.prepareStatement("select  payment_mode from PaymentMode");   
                 ResultSet  rs=pst.executeQuery();
                   //here i call that method
                    table.setModel(resultSetToTableModel(rs));
                    table.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 14));
                    while(rs.next())
                    {
                            mp.paymentmode_ComboBox.addItem(rs.getString("payment_mode"));
                    }

                   }
                    catch(SQLException e)
                    {
                        e.printStackTrace();
                    }
                    finally
                    {
                       //this method is for closing the connection
                        MSUTIL.cleanUp(con, pst, rs);
                    }

}

© www.soinside.com 2019 - 2024. All rights reserved.