我想用数据库中的值填充 jComboBox。这些值取决于文本字段中写入的文本。 例如:如果我在文本字段中写入 a,组合框将包含以 a 开头的所有值。这些值来自数据库
这是我的代码:
private void FillCombo(){
String url = "jdbc:mysql://localhost:3306/pharmacy";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "test";
String sql = "select medicinename from medicine where medicinename like '%"+jTextField5.getText()+"%'";
try{
Class.forName(driver).newInstance();
System.out.println("1");
Connection con = (Connection)DriverManager.getConnection(url,user,pass);
System.out.println("Connected");
Statement st=(Statement) con.createStatement();
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while(rs.next()){
String name = rs.getString("medicinename");
jComboBox1.addItem(name);
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}}
最佳答案
I want not just one caracter eg: if i write a, as, asp it fill aspirine myproblem is that the combobox is already filled. want it empty when i start.
只需使用 JComboBox#removeAllItems()每次敲击 JTextField
中的任意键时,都会从项目列表中删除所有项目。
要记住的要点
- 不要在每次输入新字符时加载驱动程序。将其移到
FillCombo()
方法之外。 - 使用PreparedStatement而不是使用可能导致问题的单引号查询字符串。在 Using Prepared Statements 上查找示例
- 不要忘记关闭连接、结果集和语句等资源。
- 使用finally block 来处理它或阅读更多关于Java7 -The try-with-resources Statement
关于java - 根据文本字段中的文本从数据库填充 jcombobox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23843027/