2

I've implemented a method that return the result of a query on a SQL database. I just want the method to retur only a String[] which is the result of a query that select a column on the db. Here my code:

public class DBConnection {
private static Connection con;
private static Statement st;
private static ResultSet rs;

    try
    {   
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","user","password");
        st = con.createStatement();
    }

    catch (Exception ex)
    {
        System.out.println("Error: "+ex);
    }
public ArrayList<String[]> doQuery (String query)
{
      ArrayList<String[]> v = null;
      String [] record;
      int columns = 0;
      try {
         Statement stmt = con.createStatement();    
         ResultSet rs = stmt.executeQuery(query);   
         v = new ArrayList<String[]>();
         ResultSetMetaData rsmd = rs.getMetaData(); 
         columns= rsmd.getColumnCount();            

         while(rs.next()) {   
            record = new String[columns]; 
            for (int i=0; i<colonne; i++) record[i] = rs.getString(i+1); 
            v.add( (String[]) record.clone() );
         }
         rs.close();     
         stmt.close();   
      } catch (Exception e) { e.printStackTrace(); }

      return v;
   }    

this method return an ArrayList object that contains the result of a query. Now, the question is: how can I have from this ArrayList object a String[] object that contains ONLY a column of the result?

(As information : The String[] object will be inserted in a JComboBox object)

2
  • A side note first: why do you call record.clone()? You're creating a new array anyways and clone() would just create another one - it's no deep clone, i.e. the strings are not cloned as well (which would also be unnecessary). Commented Sep 9, 2013 at 13:24
  • 3
    Already answered in SO. Check this stackoverflow.com/questions/5374311/… Commented Sep 9, 2013 at 13:26

4 Answers 4

2

I assume your question has two components: a) you want to return a string array and b) you want to return only a single column.

The answer to a) has already been given or at least hinted at.
The answer to b) would require you to know the name of the column you want to return or adjust the query.

You might change your method to something like this:

public String[] doQuery (String query, String columnName) //columnName not needed if you know the index of the column or if the name is always the same, in which case it could be some constant
{
  List<String> v = new ArrayList<String>();

  try {
     Statement stmt = con.createStatement();    
     ResultSet rs = stmt.executeQuery(query);           

     while(rs.next()) {    
        v.add( rs.getString(columnName) ); //or rs.getString(1); if you know the column is the first in the query's result
     }
     rs.close();     
     stmt.close();   
  } catch (Exception e) { e.printStackTrace(); }

  return v.toArray(new String[v.size()]); 
}    

A few notes:

  • You'd have to ensure that the column has the name you want to query it with, i.e. you can't do select columnA from ... and then call rs.getString("columnB");. If you don't know the name but know the index of the column in the resultset, use rs.getString(x); instead, where x is the one-based index.

  • instead of v.toArray(new String[v.size()]); you could also use v.toArray(new String[0]);. The difference between the two is that the former returns the array you pass as a parameter whereas the latter creates a new array internally and returns that.

Sign up to request clarification or add additional context in comments.

5 Comments

First of all I thank you for your answer. You use List<String> v = new ArrayList<String>(); Why List and not ArrayList? Thinking better, I find that I can insert the columnName in the query itself.. what do you think?
First, it is generally better to program against interfaces and not concrete implementations. All you need to know about v is, that it is a List<String> and if you later want to replace ArrayList<String> with LinkedList<String> it would be just one place that has to be changed (true, it is trivial in your case but there are others that aren't and it's just a good habit to use the interfaces where possible ;) ).
@Bernheart as for the query: you could add the column name yourself, provided you know the query selects from the correct table. Another option might be to pass the where conditions only and create query string within the method.
A good solution might be passing the table name and column name as String to the method. In this way is not necessary to write the query, but the query itself is implemented in the method. What do you think? By the way, I thank you. Your method works. Thanks
@Bernheart it might be a solution. Note, however, that you'd still have to handle cases where the column is of the wrong type or not present in the table. You might also want to consider using some ORM library (e.g. Hibernate, Eclipse Link etc.) to faciliate DB access. Btw, feel free to accept the answer, if it is what you wanted ;)
2

why not to call v.toArray(new String[0])?

3 Comments

Thank you, but if I do this and print the result, the Console will explain: Exception in thread "main" java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at java.util.Arrays.copyOf(Arrays.java:2248) at java.util.ArrayList.toArray(ArrayList.java:360) at Main.main(Main.java:20)
Did you array contain integer in it ?. If so then you will get that exception
The problem is that v is a list of string arrays, and the suggestion above would try to cast String[] to String[]. Though untested v.toArray(new String[0][]) might work.
0

pasted the solution given in link Converting 'ArrayList<String> to 'String[]' in Java

ArrayList<String> list = new ArrayList<String>();
String[] array = list.toArray(new String[list.size()]);

(or)

ArrayList<String> arrayList = new ArrayList<String>(); 
Object[] ObjectList = arrayList.toArray();
String[] StringArray = Arrays.copyof(ObjectList,ObjectList.length,String[].class);

Comments

0

On an ArrayList you can call toArray() to get an Array of its values.

This would look like this:

// create an ArrayList
ArrayList<String> theArrayList = new ArrayList<String>();
theArrayList.add("aString");
theArrayList.add("anotherString");

// get its contents as an Array
String[] theArray = new String[theArrayList .size()];
theArray = theArrayList.toArray(theArray);

You can look up more details in the Java Docu for ArrayList.toArray().

2 Comments

I've tried what have you written with the comand System.out.println(theArray).. the result is : Exception in thread "main" java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at java.util.ArrayList.toArray(ArrayList.java:361) at Main.main(Main.java:21)
If you debug into your code just before your line return v; What do you see inside of v at this point?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.