将mysql数据库中的记录显示为java中的自定义Jtable

时间:2017-04-04 09:55:04

标签: java mysql

我的数据库中有一些记录,我希望在我的java应用程序GUI中的Jtable上显示。我已经定制了Jtable并添加了一些不在我的数据库中的额外列。 请帮助。下面的代码仅显示单个列中的单个记录(特定的描述列)

    public NewJFrame() {
    ArrayList data = new ArrayList();
    initComponents();

    okay.setVisible(true);
    try {
        String myDriver = "com.mysql.cj.jdbc.Driver";
        String myUrl = "jdbc:mysql://localhost:3306/lostfound";
        Class.forName(myDriver);
        Connection c = DriverManager.getConnection(myUrl, "root", "");
        String sql = "SELECT * FROM found";
        Statement st = c.createStatement();

        // execute the query, and get a java resultset
        ResultSet rs =st.executeQuery(sql);


        while(rs.next())
        {
        String name = rs.getString("name");
        String description = rs.getString("description");
        String location = rs.getString("location");
        jTable2.getModel().setValueAt(name, WIDTH, ICONIFIED); 
        jTable2.getModel().setValueAt(description, WIDTH, ICONIFIED);   
        jTable2.getModel().setValueAt(location, WIDTH, ICONIFIED);   
        }
    }
    catch (SQLException e)
    {
        System.out.println( e.getMessage() );
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
    jTable2.show();
}

1 个答案:

答案 0 :(得分:0)

您要将 resultSet数据分配到单行和列,您需要一个row计数器&为每一行增加它,如下所示:

int row=0;
while(rs.next()) {
    String name = rs.getString("name");
    String description = rs.getString("description");
    String location = rs.getString("location");
    jTable2.getModel().setValueAt(name, row, 0);//name at column 0 always
    jTable2.getModel().setValueAt(description, row, 1);//desc at column 1 always 
    jTable2.getModel().setValueAt(location, row, 2);//location at column 2 always
    row++;//increment row counter for each record
}