Search code examples
javaapache-commons-dbutils

How do I query for a List<String> using DBUtils?


Looking over the DBUtils API docs, I cannot see if it's possible to query for a List<String> in the same way that I could query a List<MyBean> using BeanListHandler.

I could either do it be creating a Bean that wraps the String and use BeanListHandler or possibly return a List<Object[]> and fish out my Strings that way.

But is there a more direct way where DBUtils can pass back a List<String> for a query that produces a bunch of String values from a varchar table column?


Solution

  • Try a ColumnListHandler, and tell it which column to use from your query. You can pass in either the column index or column name to extract. Something like:

    List<String> strings = runner.query("SELECT my_col FROM my_table",
                                        new ColumnListHandler<String>(1));
                                        // gets first column
    

    Internally it uses ResultSet#getObject which returns a String if the selected column is a string type, so make sure you're not selecting a numeric or date type or something (and if you are, cast or otherwise convert it to a char type in the select query).