Get selected JComboBox value and add to SQL query for second JComboBox

前端 未结 1 1683
悲&欢浪女
悲&欢浪女 2021-01-26 11:27

I am designing a simple database application that features 2 jComboBoxes in the GUI. The first jComboBox is populated with the results of an SQL query. I would like the second j

相关标签:
1条回答
  • 2021-01-26 11:46

    I'm assuming that you'd like select a value from your first JComboBox then click on a button to process your selected data and load new data to your second JComboBox.

    In this case you need an ActionListener to your JButton instead of your JComboBox:

    jButton1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            selectedName = (String) jComboBox1.getSelectedItem();                
        }
    });
    

    You also need to store your selected value in a variable. The getSelectedItem() method returns an Object so it needs to be cast to a String in your case.

    Since we added an ActionListener to a button you dont need this one:

    jComboBox1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jComboBox1ActionPerformed(evt);
        }
    });
    


    In your createConnection class (by naming convention class names should start with a capital letter):

    If you are not using try-with-resources statement you should close your connections after the catch block.

        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
    
            }
        }
    

    You need to pass your selectedName variable to getEmpLocation() method:

    public List<String> getEmpLocation(String name) {
    

    You should use a PreparedStatement instead of Statement:

    String query = "SELECT first_name FROM employees WHERE last_name = ?";
    PreparedStatement ps = conn.prepareStatement(query);
    ps.setString(1, name);            
    ResultSet results = ps.executeQuery();
    

    To be honest I don't know what you'd like to achieve with your select queries. First, this select query won't work. Table name is LOCATIONS instead of location, and it doesnt have a column called emp_name.

    "SELECT country_id FROM hr.location WHERE hr.location.emp_name = ?"
    

    If you'd like to get locations you should use a query like this:

    "SELECT dep.department_name, loc.city, cou.country_name
     FROM employees emp, departments dep, locations loc, countries cou
     WHERE emp.last_name = ?
     AND emp.department_id = dep.department_id 
     AND dep.location_id = loc.location_id
     AND loc.country_id = cou.country_id"
    

    You can choose which location you'd like to use department, city or country name. But my main problem is that if you select last names first and put them in a JComboBox it is most likely you will get only one row of data, so there is no point in using the second JComboBox. Let's approach this problem from the other side. What if you select location first and then select your employee. That could solve this issue.


    Quick Example: You select all first names from database, then you can select proper last name.

    Selecting all first name from database:

        public List<String> getEmpFirstName() {
            List<String> list = new ArrayList();
            Connection conn = createConnection();
    
            try {
                Statement stmt = conn.createStatement();
                String query = "SELECT DISTINCT first_name "
                                + "FROM hr.employees "
                                + "ORDER BY first_name";
                ResultSet results = stmt.executeQuery(query);
    
                while (results.next()) {
                    list.add(results.getString("first_name"));
                }
            } catch (Exception e) {
                System.out.println("Exception = " + e);
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }                    
                }
            }
            return list;
        }
    

    Selecting last name(s) based on first name using PreparedStatement:

        public List<String> getEmpLastName(String name) {
            List<String> list = new ArrayList();
            Connection conn = createConnection();
    
            try {
                String query = "SELECT last_name "
                                + "FROM employees "
                                + "WHERE first_name = ?";
                PreparedStatement ps = conn.prepareStatement(query);
                ps.setString(1, name);            
                ResultSet results = ps.executeQuery();
    
                while (results.next()) {
                    list.add(results.getString("last_name"));
                }
            } catch (Exception e) {
                System.out.println("Exception = " + e);
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }                    
                }
            }
            return list;
        }
    

    Update your ActionListener:

        jButton1.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // Store selected value
                    selectedName = (String) jComboBox1.getSelectedItem();
    
                    // Create Connection and pass selected value to getEmpLastName
                    createConnection c1 = new createConnection();
                    names = c1.getEmpLastName(selectedName);
    
                    // Clear your second comboBox and fill with data
                    jComboBox2.removeAllItems();                
                    for (String lastName : names) {
                        jComboBox2.addItem(lastName);
                    }              
                }
            });    
    

    Try to select common names like Alexander, David, James, John, Julia and so on.

    0 讨论(0)
提交回复
热议问题