javaswingjdbcjcomboboxcomboboxmodel

How do I insert data from mysql into the combobox?


What's wrong with my code here?

I'm trying to insert data from the mysql into the combobox in netbean

private void btnSandoghMousePressed(java.awt.event.MouseEvent evt) {                                        
    try {
        String query = "SELECT `AccountType` FROM `account`"; 
        con = Connect.ConnectDB();
        PreparedStatement stm = con.prepareStatement(query); 
        pst = con.prepareStatement(query);                
        ResultSet rs = pst.executeQuery(query);
        ArrayList<String> groupNames = new ArrayList<String>(); 
        while (rs.next()) { 
            String groupName = rs.getString(4); 
            groupNames.add(groupName);
        } 
        DefaultComboBoxModel model = new DefaultComboBoxModel(groupNames.toArray());
        cmbSemetarID.setModel(model);
        rs.close();    
    } catch (SQLException e) {
    System.err.println("Connection Error! it's about date");
    }
}

Solution

  • You get problems sometimes you try to use Model this way or using a Vector. Better try to do something like,

      private void btnSandoghMousePressed(java.awt.event.MouseEvent evt){                                        
        try {
            String query = "SELECT `AccountType` FROM `account`"; 
            con = Connect.ConnectDB();
            PreparedStatement stm = con.prepareStatement(query); 
            pst = con.prepareStatement(query);                
            ResultSet rs = pst.executeQuery(query);
            DefaultComboBoxModel model = new DefaultComboBoxModel();
            while (rs.next()) { 
                String groupName = rs.getString(4); 
                model.add(groupName);
            } 
    
            cmbSemetarID.setModel(model);
            rs.close();    
        } catch (SQLException e) {
        System.err.println("Connection Error! it's about date");
        }
    }