0

I'm reading a SQLite DB in java and have a result-set of an integer type and string type.

The result-set is never the same size, so a string array wouldn't work I believe.

What I have is [Int ItemID] [String ItemName] and want to be able to get the resultset to save these to some sort of map, list or array so that I can output them to the user as called upon.

I attempted the below with a string array; but like I said about - It's never the same size as its a search query against a SQLite DB.

Connection connection = DriverManager.getConnection("jdbc:sqlite:ItemDB.db");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
String queryResults[][] = null;
while (resultSet.next()) {
    queryResults[current][0] = resultSet.getString("itemId");
    queryResults[current][1] = resultSet.getString("itemName");
    current++;
}
resultSet.close();
statement.close();
connection.close();
return queryResults;

If there's a better way to achieve what I'm looking for I'm all ears!

Thanks in advance!

1 Answer 1

2

Use a map:

Map<Integer, String> dataMap = new HashMap<>();
while (resultSet.next()) {
    dataMap.put(resultSet.getInt("itemId"), resultSet.getString("itemName"));
}

Edit: You can use a TreeMap if you need the keys to be sorted.

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

6 Comments

Awesome! That's what I'm looking for. Is there a way to sort it by Integer after? It takes 1000 and puts it after 1 unfortunately.
@DotSlashShell use a TreeMap instead of a HashMap.
Order the response in your SQL ("... ORDER BY some_column") and then use a LinkedHashMap vs. HashMap to maintain insertion order.
TreeMap did it for me!
FYI, a TreeMap is a SortedMap, so its keys are kept in sorted order. For more info, search Stack Overflow.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.