0

我已经四处寻找这个问题的答案,但无济于事。当我编译它时,它只返回数据库中表的最后一行,而不是我期望的整个列的列表。我相信问题出在此处。如果我能列出该列中的所有内容,我将不胜感激。

String query = "SELECT contact_id, first_name, last_name FROM my_contacts";
ResultSet rs = statement.executeQuery(query);

while (rs.next())
{
    System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
    String name = rs.getString(2) + " " + rs.getString(3);
        names = new JComboBox();
        names.addItem(rs.getString("first_name"));
}//end while
4

2 回答 2

3

When I compile this, it just returns the last row of my table in the database and not a list of the entire column as I expect. I believe the problem is from here..

while (rs.next())
{
    System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
    String name = rs.getString(2) + " " + rs.getString(3);
        names = new JComboBox();
        names.addItem(rs.getString("first_name"));
}
  • your code created a new instance of JComboBox, in each of loop inside while (rs.next()){

  • create JComboBox as local variable, then just to add Items in while-loop to instance that already exist and is intialized

  • best of ways is by using DeafultComboBoxModel for add / remove / modify an Items for JComboBox

于 2013-05-20T15:02:38.877 回答
0

使用此代码启动并运行所有内容。

        try { 
             Class.forName("com.mysql.jdbc.Driver");

             Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/recall", "username", "password");

             Statement statement = connection.createStatement();
             String query = "SELECT * FROM names";
             ResultSet rs = statement.executeQuery(query);

             while (rs.next())
             {      
                String name = rs.getString("name");         
                names.addItem(rs.getString("name"));
             }//end while
             connection.close();
             } catch (Exception e) {
                  e.printStackTrace();
             }
于 2013-05-23T11:10:32.807 回答