我试过从MySQL数据库中检索数据到JComboBox,但是我没有得到它,因为当我在JTextField中编写一个isbn来搜索一本书时,会出现4次所有的id,最后出现2次我想要的id。我想把数据放到JComboBox中,只需要有我正在搜索的isbn的id,boxBookId就是我的JComboBox。我用上网本。有人能帮我吗?提前谢谢!
这是我的代码:
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);
}
}
最佳答案
在将查询结果添加到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并在每次调用之前重新创建语句)。关于java - 如何从数据库获取值到jcombobox?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33961142/