0

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.

2
  • I was not sure to create an int variable for the amount of cells the column airport has. So I could use this in the for loop. Commented Dec 3, 2014 at 12:33
  • column variable should be first defined than it should be used as it will give compile time error. Commented Dec 3, 2014 at 12:50

1 Answer 1

3

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"));                                 
}
Sign up to request clarification or add additional context in comments.

3 Comments

Could you explain why it is better to use an ArrayList over an array?
because The capacity of an Array is fixed. Where as,ArrayList can increase and decrease size dynamically.
@Mr.Goose array has a fixed length and you need to define the size of array. But you don't need to bother about the length of ArrayList, and no need to define it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.