如何从数据库获取值到jcombobox?

时间:2015-11-27 16:06:46

标签: java mysql jcombobox

我试图将数据从MySQL数据库检索到JComboBox但是我没有得到它,因为当我将一个isbn写入JTextField来搜索一本书时,出现了4次所有id并最终出现了我想要的ID但是2次。我想把数据放到JComboBox中,只有我正在搜索isbn的id,boxBookId是我的JComboBox。我使用NetBeans。有人可以帮帮我吗?提前谢谢!

这是我的代码:

private void fieldIsbnKeyReleased(java.awt.event.KeyEvent evt) {                                      
    try {
        String url = "jdbc:mysql://localhost/library";
        Connection con = DriverManager.getConnection(url,"root","");
        Statement stm = con.createStatement();

        String sql = "SELECT id, book, author FROM books WHERE isbn LIKE '%" +fieldIsbn.getText()+ "%' ";
        String sql2 = "SELECT COUNT(isbn) FROM books WHERE isbn LIKE '%" +fieldIsbn.getText()+ "%' ";

        pstm = con.prepareStatement(sql);
        rs = pstm.executeQuery();
        pstm2 = con.prepareStatement(sql2);
        rs2 = pstm2.executeQuery();

        while (rs.next()) {
            boxBookId.addItem(rs.getString("id"));
            String val1 = rs.getString("book");
            fieldBook.setText(val1);
            String val2 = rs.getString("author");
            fieldAuthor.setText(val2);
        }
        while (rs2.next()) {  
                fieldAvailableBooks.setText(rs2.getString(1));
        } 
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex);
    } 
}

1 个答案:

答案 0 :(得分:1)

在将查询结果添加到boxBookId之前,您需要删除所有现有元素,例如通过在while循环之前调用boxBookId.removeAllItems()(以防止在查询失败时删除它们)。

至于我提到的安全问题(你应该自己仔细阅读),使用PreparedStatement设置参数(只构造一次并重用它):

//outside your method: construct this only once and reuse inside your method
pstm = con.prepareStatement("SELECT id, book, author FROM books WHERE isbn LIKE ?");

//in your method:
pstm.setString(1, "%" + fieldIsbn.getText() + "%" );
rs = pstm.executeQuery();

正如您所看到的,我重复使用了您已创建的PreparedStatement pstm。关键是重用它并使用它来设置参数。否则使用PreparedStatement没有多大意义(我的意思是直接将参数值附加到SQL并在每次调用之前重新创建语句)。