简体   繁体   中英

Display records from mysql database to a custom Jtable in java

I have some records in my database, which i would like to display on a Jtable in my java application GUI. I have customized the Jtable and added some extra columns which are not in my database. Kindly assist. The code below only displays a single record in a single column(description column to be specific)

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

You are assigning the resultSet data to a single row and column , you need a row counter & increment it for each row, as shown below:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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