Jonathan Solorzano
Jonathan Solorzano

Reputation: 7022

How to get all the values of a table's column from a sqlQuery in Java?

what I want is to get all the values that are into a column that i call in query from Java to SQL Server, I think it is like this:

public ArrayList createArray(ResultSet data){
    try {
        ArrayList arrayData = (ArrayList) data.getArray(1);//get all the data from the resultSet that's into the column 1
        return arrayData;
    } catch (SQLException ex) {/*Error message*/return null;}
}

But actually I don't know what does getArray() returns, and I don't find any information about it. If someone can help, I'll be thankful. Also if getArray() doesn't work like I think it does, could you please tell me how to do what I want?

Upvotes: 0

Views: 4695

Answers (2)

SparkOn
SparkOn

Reputation: 8946

try something like this :

List list = new ArrayList();
while (resultSetObject.next()) {
    list.add(resultSetObject.getString("columnName"));
} 

You can convert it to String array if you want which I think is not necessary

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

Upvotes: 0

clay
clay

Reputation: 20370

Here is the standard jdbc approach, which requires lots of boilerplate code and temporary variables, and the same thing with a more elegant add-on library, jdbi, which lets you use a much simpler fluent API:

jdbi approach:

public static List<String> jdbiEmployeeNameQuery(Handle h) {
    return h.createQuery("select name from employees order by id").map(StringMapper.FIRST).list();
}

jdbc approach:

public static List<String> jdbcEmployeeNameQuery(Connection dbConnection) throws SQLException {
    try (Statement s = dbConnection.createStatement()) {
        try (ResultSet rs = s.executeQuery("select name from employees order by id")) {
            List<String> names = new ArrayList<String>();

            while (rs.next()) {
                names.add(rs.getString(1));
            }

            return names;
        }
    }
}

Upvotes: 1

Related Questions