无法将数据库数据填充到jcombobox中

0lvr5msh  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(430)

我无法填充 JComboBox 数据库数据。这是我用数据库数据填充组合框的代码。我可以连接到数据库。catch块用于显示错误消息。所发生的是,错误消息没有弹出,当我的应用程序运行时,组合框是空的。这是我的数据库表,我想将这些名称填充到组合框中。

package testing;

  import java.awt.EventQueue;
  import java.sql.Connection;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;

  import javax.swing.JFrame;
  import javax.swing.JOptionPane;
  import javax.swing.JPanel;
  import javax.swing.border.EmptyBorder;
  import javax.swing.JComboBox;

 public class combobox extends JFrame {

/**
 * 
 */
  private static final long serialVersionUID = 1L;
  private JPanel contentPane;
  private static JComboBox combobox_database;
  static Connection conn = null;

/**
 * Launch the application.
 */
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                sqliteconnection.dbConnector();
                fillcombobox();
                combobox frame = new combobox();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
  }

/**
 * Create the frame.
 */
public combobox() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 619, 524);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JComboBox combobox_database = new JComboBox();
    combobox_database.setBounds(208, 87, 175, 22);
    contentPane.add(combobox_database); 
}

public static void fillcombobox(){
    try{
        String sql = "SELECT name FROM testing_table";
        PreparedStatement pst = conn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();

        while(rs.next()){
         String s = rs.getString(2);
         combobox_database.addItem(s);

        }

        pst.close();
        rs.close();
        conn.close();

    }catch (Exception e){
        JOptionPane.showMessageDialog(null, e);
    }

   }

}

2w3rbyxf

2w3rbyxf1#

你的查询只选择一个属性, name ,所以 columnIndex 传递给 getString() 应该是 1 .

while(rs.next()) {
    String s = rs.getString(1);
    combobox_database.addItem(s);
}

如本文所述,您还可以使用 columnLabel ; 这里给出了一个完整的例子;这个相关的例子使用jpa。

8fsztsew

8fsztsew2#

我看到的是,“jcombobox combobox\u database”是在另一个方法中定义和初始化的,因此fillcombobox()方法没有引用它。我打赌你的程序有一些编译错误。

相关问题