Archive for December 2014

How to populate JTable with records from database in Java?

public class PopulateTableFromDb extends JFrame{
    public static void main(String args[]) {
        new PopulateTableFromDb();
    }
    
    public PopulateTableFromDb() {        
       String[][] rowData = readDB();
       String columnNames[] = { "Name", "Phone", "Address" };
       JTable table = new JTable(rowData, columnNames);
       JScrollPane scrollPane = new JScrollPane(table);
       
       getContentPane().setLayout(new GridLayout(0, 1));
       add(scrollPane, BorderLayout.CENTER);
       
       setVisible(true);
       setSize(400, 400);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    private static String[][] readDB() {
        Connection connect;
        String Username="root";
        String Password="";
        String URL="jdbc:odbc:phonebook";
        int i = 0;
        String[][] storeData = new String[10][3];
            
        try {
            connect = DriverManager.getConnection(URL,Username,Password);
            Statement st = connect.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM phonebook");

            while(rs.next())
            {
               String[] temp = new String[10];
               temp[0] = rs.getString("name");
               temp[1] = rs.getString("phone");
               temp[2] = rs.getString("address");
               
               storeData[i] = temp;
               i++;
            }     
        } 
        catch(SQLException e) {
            System.out.println("Error");
        } 
        
        return storeData;
    }
}
www.000webhost.com