[Updated: 01/06/2013] How to update jtable dynamically from Oracle , MySQL (Database)?

UPDATED: 31 October 2010
Once i found updating jTable dynamically was tough task. Now I'll help you to understand that code. I'm considering that you are working in Integrated Development Environment. Don't waste your time by coding your project in text editor like notepad or so.

jtable, java, swing
jTable

I'm considering that you already declared jTable in your code. I'm updating the jTable data on formWindowOpened. You can set your own event for the code below.

// import database class as per oracle and mysql selection.
private void formWindowOpened(java.awt.event.WindowEvent evt) {
        Object[][] rowData = new Object[2][2];
        Object columnNames[] = {"Client ID", "Client Name"};
        int i = 0;
        try {
            /*
             * It's my own function to load database connection.
             * You have to load database driver and connection.
             * public static final Connection getDatabaseConnection() throws Exception {
             * Class.forName(dbdriver);
             * return DriverManager.getConnection(dbhost, dbusername, dbpassword);
             * }
             */
            Connection con = variables.getDatabaseConnection(); 
            PreparedStatement client_stmt = con.prepareStatement("select idclients,ClientName from clients limit 0,2");
            ResultSet client_rs = client_stmt.executeQuery();
            while (client_rs.next()) {
                rowData[i][0] = client_rs.getString("idclients");
                rowData[i][1] = client_rs.getString("ClientName");
                i++;
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        DefaultTableModel tm = new DefaultTableModel(rowData, columnNames);
        jTable1.setModel(tm);       
}

This is it. Choose your event to load the data. Don't forget to change the database query and its column name. Subscribe to Google plus and Facebook for more stuffs...

0 comments :