我在数据库中有一个表,其中 2column
是carbrand
和carmodel
,我在表中插入了这些数据:
INSERT INTO cars ('carbrand', 'carmodel')
VALUES('Honda', 'City'),
('Honda', 'Civic'),
('Honda', 'Jazz'),
('Toyota', 'Corolla'),
('Toyota', 'Altis');
我希望我的第一个 ComboBox 包含汽车品牌,然后用它对应的汽车型号填充第二个 ComboBox,反之亦然。目前这是我迄今为止编写的代码片段。
private void PopulateCarBrandComboBox() {
String sql = "SELECT DISTINCT carbrand FROM cars";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
String nme = rs.getString("carbrand");
carbrandComboBox.addItem(nme);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void PopulateCarModelComboBox() {
String sql = "SELECT * FROM cars WHERE carbrand = ?";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, (String)carbrandComboBox.getSelectedItem());
rs = pst.executeQuery();
while(rs.next()) {
String nme = rs.getString("carmodel");
carmodeleComboBox.addItem(nme);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}