Skip to content
Advertisement

Save a Resultset to an Array in java

I want to save the result of a whole Mysql table in an array

    String sDriver = "com.mysql.jdbc.Driver";
    String sURL = "jdbc:mysql://www.odorxd.xyz:3306/u218933149_odor_base";

    try {
        Class.forName(sDriver).newInstance();
        Connection con = DriverManager.getConnection(sURL, "u218933149_estenoesodor", "Tsunayoshi27?");

        PreparedStatement stmt = null;
        ResultSet rs = null;

        stmt = con.prepareStatement("SELECT * FROM justname");
        rs = stmt.executeQuery();

        while (rs.next()) {

            for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
                System.out.print(rs.getString(x) + "t");

            }

            System.out.println("");

        }

    } catch (SQLException sqle) {
        sqle.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

it returns this to me from the database

run: brandon Brandon Julio

Daniel
BUILD SUCCESSFUL (total time: 1 second)

I want to save what is in the database in an array to be able to implement it with a sort and search method

String str[] = { "Ajeet", "Steve", "Rick", "Becky", "Mohan", "Brandon", "Brandon Jesus", "Brandon Flores", "Brandon Flores Flores"};
    String temp;
    System.out.println("Strings in sorted order:");
    for (int j = 0; j < str.length; j++) {
       for (int i = j + 1; i < str.length; i++) {
        // comparing adjacent strings
        if (str[i].compareTo(str[j]) < 0) {
            temp = str[j];
            str[j] = str[i];
            str[i] = temp;
        }
       }
       System.out.println(str[j]);
    }   

that’s why I need to save it in an array

I would appreciate any criticism or help as you do not have an idea, thank you

Advertisement

Answer

You can use a List.

List<String> list = new ArrayList<>();
while (rs.next()) {
    for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
        String str = rs.getString(x)
        list.add(str);
        System.out.print(str + "t");
    }
    System.out.println();
}
String[] arr = list.toArray(new String[0]);
String temp;
// ... sort
Advertisement