How to populate data in a JComboBox?

后端 未结 3 991
春和景丽
春和景丽 2021-01-16 00:07

I have created a GUI and have a database located externally in which I fetch data from. I am using the GUI builder in NetBeans to do this. Does anyone know of a simple way t

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-16 00:13

    It might be that your SELECT query returns no results. To verify this, you can add logging statements inside the while (rs.next()) loop. My SQL knowledge is a bit rusty, but I remember using ' (single quotes) for string literals, whereas you use " (double quotes) in your statement.

    Besides that, I see several things which could cause problems:

    • The SQL code for PreparedStatement should not be created by string concatenation. Instead, use ? for parameter values which will be substituted into the statement, e.g.

      stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?");
      stmt.setString(1, type); // first (and only) parameter
      rs = stmt.executeQuery();
      
    • It is strongly recommended that you explicitly close JDBC resources after being done with them. For this, you need to add a finally block after the catch (SQLException ...), e.g.

      } finally {
           try {
               if (rs != null) rs.close();
           } catch (SQLException ignore) {}
      
           try {
               if (stmt != null) stmt.close();
           } catch (SQLException ignore) {}
      
           try {
               if (conn != null) conn.close();
           } catch (SQLException ignore) {}
      }
      

      or, preferrably, use the try-with-resources statement (if you are using Java 7 and higher):

      try (Connection con = DriverManager.getConnection(...)) {
          // ...
          try (PreparedStatement stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?")) {
              // ...
              try (ResultSet rs = stmt.executeQuery()) {
                  while (rs.next()) {
                      // processing
                  }
              }
          }
      } catch (SQLException) {
          Logger....;
      } // notice no finally block; resources are closed automatically
      

提交回复
热议问题