获取选定的JComboBox值并添加到第二个JComboBox的SQL查询

时间:2017-01-26 22:26:45

标签: java sql oracle swing class

我正在设计一个简单的数据库应用程序,它在GUI中有2个jComboBox。第一个jComboBox填充了SQL查询的结果。我希望第二个jComboBox填充第二个查询的结果,该查询在第一个框中包含用户选择的值,但我无法让它工作。

我创建了2个类,一个绘制GUI并包含main方法,另一个类查询我的Oracle数据库。

我的GUI类:

public class TestUI extends javax.swing.JFrame {
     // Create new form TestUI
    public TestUI() {
        initComponents();
    }

    @SuppressWarnings("unchecked")

    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jComboBox1 = new javax.swing.JComboBox<>();
        jTextField1 = new javax.swing.JTextField();
        jComboBox2 = new javax.swing.JComboBox<>();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        // Combo box 1 population

        jComboBox1.removeAllItems();
        createConnection c1 = new createConnection();
        c1.getEmployee().forEach((employee) -> {
            jComboBox1.addItem(employee);
        });
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        // ComboBox 2 population

        jComboBox2.removeAllItems();


    }                     

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add handling code here:
    }                                    

    public static void main(String args[]) {
        DRAW GUI
    }
}

我的数据库类:

import java.util.List;
import java.util.ArrayList;
import java.sql.*;

public class createConnection {

    String empName;

    public Connection createConnection() {
        try {
            Class.forName(driver);
            java.sql.Connection conn = DriverManager.getConnection(DB_URL, DB_username, DB_password);
            return conn;
        } catch (ClassNotFoundException | SQLException e) {
            return null;
        }
    }

    // ComboBox 1
    public List<String> getEmployee() {
        List<String> list = new ArrayList();
        Connection conn = createConnection();
        try {
            Statement stmt = conn.createStatement();
            String query = "SELECT * FROM hr.employees ORDER BY last_name";
            ResultSet results = stmt.executeQuery(query);
            while (results.next()) {
                list.add(results.getString("last_name"));
            }
        } catch (Exception e) {
            System.out.println("Exception = " + e);
        }
        return list;
    }

    // Combo Box 2
    public List<String> getEmpLocation() {
        List<String> list = new ArrayList();
        Connection conn = createConnection();
        try {
            Statement stmt = conn.createStatement();
            String query = "SELECT country_id FROM hr.location WHERE hr.location.emp_name = " + empName;
            ResultSet results = stmt.executeQuery(query);
            while (results.next()) {
                list.add(results.getString("last_name"));
            }
        } catch (Exception e) {
            System.out.println("Exception = " + e);
        }
        return list;
    }    
}

我遗漏了不相关的代码,如数据库连接变量和GUI坐标等。

我想知道如何在数据库类中正确获取getEmpLocation()方法来填充第二个ComboBox。这将涉及向两个类添加代码并传递变量值,但我无法弄明白!任何帮助将在这里非常感谢。

1 个答案:

答案 0 :(得分:0)

我假设您要从第一个JComboBox中选择一个值,然后单击一个按钮来处理您选择的数据并将新数据加载到您的第二个JComboBox。

在这种情况下,你需要一个ActionListener到你的JButton而不是你的JComboBox:

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

您还需要将所选值存储在变量中。 getSelectedItem()方法返回一个Object,因此需要在您的情况下将其强制转换为String。

由于我们向一个按钮添加了一个ActionListener,你不需要这个:

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


createConnection类中(通过命名约定类名称应以大写字母开头):

如果您没有使用try-with-resources语句,则应在catch块之后关闭连接。

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

        }
    }

您需要将selectedName变量传递给getEmpLocation()方法:

public List<String> getEmpLocation(String name) {

您应该使用PreparedStatement而不是Statement:

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

说实话,我不知道你想用你的选择查询做什么。首先,此选择查询将不起作用。表名是LOCATIONS而不是location,它没有名为emp_name的列。

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

如果您想获取位置,请使用以下查询:

"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"

您可以选择要使用部门,城市或国家/地区名称的位置。但我的主要问题是,如果你先选择姓氏并将它们放在JComboBox中,那么你很可能只得到一行数据,所以使用第二个JComboBox没有意义。让我们从另一方面解决这个问题。如果先选择位置然后选择您的员工,该怎么办?这可以解决这个问题。


快速示例: 您从数据库中选择所有名字,然后您可以选择正确的姓氏。

从数据库中选择所有名字:

    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;
    }

使用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;
    }

更新你的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);
                }              
            }
        });    

尝试选择像Alexander,David,James,John,Julia等常用名称。