Skip to content

How would I get multiple results from a MySQL table? [closed]

Say I have 2 columns, the first one is ID and the second one is colour.

How would I search for a specific colour and get all of the id’s that are in the same row as the colour?

How would I turn the results into an array?

I know how to do a simple string.

try {
    PreparedStatement ps = plugin.SQL.getConnection().prepareStatement("SELECT ID FROM playerinfo WHERE COLOUR = ?");
    ps.setString(1, colour);
    ResultSet rs = ps.executeQuery();
    int id = 0;
    if ( {
        id = rs.getInt("ID");
        return id;
} catch (SQLException e) {

This is what it should look like

id colour
 1 **red**
 2 blue
 3 green
 4 **red**
 5 **red**
 6 blue

 **red** = highlighted (but we don't know why)



try (java.sql.Connection conn = plugin.SQL.getConnection();
     PreparedStatement ps = conn.prepareStatement("SELECT ID FROM playerinfo WHERE COLOUR = ?");) {
    ps.setString(1, colour);
    java.util.ArrayList<Integer> ids = new ArrayList<>();
    ResultSet rs = ps.executeQuery();
    while ( {
catch (SQLException e) {
  • Use try-with-resources to make sure that you close the PreparedStatement and the Connection.
  • Each call to method next() (in ResultSet) will return the next row in the result set. Extract the ID from the row and add it to the ArrayList.
  • If you want an array, rather than ArrayList, you can convert ArrayList to array with one of the toArray methods in class ArrayList.

Maybe this will also help:

7 People found this is helpful