Rafael
Rafael

Reputation: 802

Storing a SQL column into a java array

I want to store a sql column into an array using a method in java

my code:

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;
    }

What I want: In a for loop I would like to add all the airport names 1 by 1 into the array so I can later on call this method to fill in a jCombobox.

Upvotes: 0

Views: 6404

Answers (1)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35597

You can do something like following.

int j=0;
while (rs.next()) {      
   airport[j] = rs.getString("airportname");// get value in airportname column
                                            // and add to array
   j++;
}

Instead of array it is better to use a ArrayList

Eg:

List<String> airPorts=new ArrayList<>();
 while (rs.next()) {      
   airPorts.add(rs.getString("airportname"));                                 
}

Upvotes: 3

Related Questions