Skip to content
Advertisement

Adding distinct data to jComboBox from database

I have a jComboBox which i want to fill up with the departments of the students in a database. Now the same department occurs many times in the table so i want each department name to go only once to the list of items. The present code i wrote is not giving the desired result. It puts the same department name multiple times on the ComboBox list. How can i solve this? My code to fetch department names is given below:

 conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydaatabase1","root","Password123");
            String sql1 = "select distinct (dept) from droptest";
            PreparedStatement pss = conn.prepareStatement(sql1);
            ResultSet rs = pss.executeQuery(sql1);
            while(rs.next())
            {
                String d = rs.getString("dept");
                jComboBox1.addItem(d);
            }

Advertisement

Answer

I guess, you need use group by in select data…

select columnName from tablename Group by columnName

    Select dept 
    From droptest
    Group by dept 

Group by is like distinct

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement