DotSlashShell
DotSlashShell

Reputation: 35

How to save int and string columns in a java array / list?

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!

Upvotes: 0

Views: 93

Answers (1)

Jason
Jason

Reputation: 11832

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.

Upvotes: 2

Related Questions