我正在尝试从数据库中选择项目的名称,然后将其保存到数组中,以便以后将其添加到JComboBox中,但是由于某种原因,它根本没有从数据库中获取它。
这是应该执行此操作的部分代码:
public BirthdayForm()
{
super("Birthday Party Supplies Rental Form");
String url = "jdbc:mysql://localhost/";
String dbName = "partySupplies";
String driver = "com.mysql.jdbc.Driver";
String username = "root";
String pw = "";
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,username,pw);
setLayout(new FlowLayout());
String[] list = null;
chooseItem = new JLabel("Choose Item:");
String selectSQL = "SELECT productName FROM birthday where productName = ?";
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery(selectSQL );
while (rs.next()) {
String name = rs.getString(2);
System.out.println(name);
for(int i=0; i<8; i++){
list[i] = name;
}
}
items = new JComboBox(list);
chooseQuantity = new JLabel("Choose Quantity:");
quantity = new JTextField("1");
choose = new JPanel();
choose.setLayout(new GridLayout(1,4));
choose.add(chooseItem);
choose.add(items);
choose.add(chooseQuantity);
choose.add(quantity);
add(choose);
//other codes
最佳答案
您必须从数据库中像这样选择它。
combobox.addItem(rs.getString("items"));
它从结果集中获取“项目”,并将其放入字符串中,并将其添加到组合框中。
关于java - 从数据库中选择并在combobox-GUI中显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29881684/