How to Store MySQL query into Java array?

10,482

This should work better. See how you first create your ArrayList of String by iterating over your ResultSet, and once your list is complete you can create the Array of Strings.

ArrayList<String> list= new ArrayList<String>();
while (rs.next()) {
    list.add(rs.getString("exercise_id"));   
} 

String[] result = new String[list.size()];
result = list.toArray(result);

for(int i =0; i<result.length; i++){
    System.out.println(result[i]);
}

BTW: your finally block is unsafe. If rs.close() fails you won't close your connection.

Share:
10,482
user2221016
Author by

user2221016

Updated on June 04, 2022

Comments

  • user2221016
    user2221016 almost 2 years

    I've found suggestions online to store the queried data into an ArrayList and then to convert the ArrayList into an Array. Below is the code that I have and it appears that I'm not doing this correctly. The SQL syntax is correct (I tested in my MySQL). Any suggestions on how to correct my code would be helpful, thanks!

    public static void dxNameExerciseID(){
        //String dxName = name;
        //String result = null;
    
        try{
            con = DriverManager.getConnection(url, user, password);  
            pst = con.prepareStatement("SELECT * FROM exercise,condition_exercise,diagnosis WHERE exercise.exercise_id = condition_exercise.exercise_id_fk AND condition_exercise.diagnosis_id_fk = diagnosis.diagnosis_id AND diagnosis.diagnosis_name = 'Adductor Strain';");
            rs = pst.executeQuery();  
    
            ArrayList<String> list= new ArrayList<String>();
            while (rs.next()) {
                list.add(rs.getString("exercise_id"));
    
                String[] result = new String[list.size()];
                result = list.toArray(result);
    
                for(int i =0; i<result.length; i++){
                    System.out.println(result[i]);
                }   
            }   
    
        }catch(SQLException ex){
        }finally {
            try {
                if (rs != null){
                    rs.close();
                }
                if (pst != null){
                    pst.close();
                }
                if (con != null){
                    con.close();
                }
            }catch(SQLException ex){
            }
        }
    
    //return result;  
    

    }