我想使用array
java
我的代码:
public static String[] getAirports() {
String airport[];
try {
String sql = "SELECT airportname FROM luggageApp.airport";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DatabaseManager.openConnection();
Statement statement = connection.createStatement();
PreparedStatement pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
airport[] = new String[columns];
while (rs.next()) {
for (int j = 1; j < columns; j++) {
airport[j] = rs.getString(j);
}
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return airport;
}
我想要的是什么: 在for循环中,我想将所有机场名称1逐一添加到数组中,以便稍后我可以调用此方法来填充jCombobox。
答案 0 :(得分:3)
您可以执行以下操作。
int j=0;
while (rs.next()) {
airport[j] = rs.getString("airportname");// get value in airportname column
// and add to array
j++;
}
而不是array
,最好使用ArrayList
例如:
List<String> airPorts=new ArrayList<>();
while (rs.next()) {
airPorts.add(rs.getString("airportname"));
}