Turning a ResultSet into 2DArray/HashMap/Lists of Lists - java

I think I've become code-blind.
I'm currently doing a small project with a friend and we're using JDBC to select from a mySQL database.
What I want is that after running the select statement, I get some sort of '2D' list of all the data back.
I think I want something returned like this -
array[columnName][all of the data inside the selected column]
Pseudo Code
// Count all rows from a column
// Count the columns selected
// Adds the column names to 'array'
for(int i = 1; i <= columnCount; i++)
columns.add(resultSetMeta.getColumnName(i));
// Adds the results of the first column to the 'array'
// How can I add the results from n columns?
for(int i = 1; i <= rowCount; i++ ) {
while (resultSet.next())
rows.add(resultSet.getString(i));
}
columnsAndRows.put(columns, rows);
What is the most appropriate data type to use to 'replicate' a table - ArrayLists, Arrays, or HashMaps?
What's the best way of making a ResultSet into a 2D datatype?
When iterating through a ResultSet, how can I move to the next column?

you can use hashmap for key value pairs, where as key you put your resultset metadata and values as resultset values.
HashMap<String, Object> p = new HashMap<String, Object>();
p.put("ResultSetkey1","ResultSetvalue1");
p.put("ResultSetkey2","ResultSetvalue2");
Also I would like to say use ResultsetUtils ResultsetUtils

Related

Iterating over values in a HashMap stored within an ArrayList

Bit of a beginner's questions but...
I have a ResultSet object that I return from a database - 3 columns of 30 rows.
I retrieve the following dataset:
using the following:
try {
preparedStatement = conn.prepareStatement(
sqlStatement,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = preparedStatement.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
while(rs.next()) {
HashMap row = new HashMap(columns);
for(int i=1; i<=columns; ++i){
row.put(md.getColumnName(i),rs.getObject(i));
}
list.add(row);
}
...and I return it as an ArrayList
...which, when debugging, displays as follows:
I want to be able to iterate over the HashMap values, in pseudo code:
get key 0
get value 0, 1 & 2
use these as test data
if no luck then try key 2
This shouldn't be hard I know, I'm just struggling to find the best way of iterating over an ArrayList of HashMaps
You are using raw types, and your IDE or compiler are throwing you tons of warnings about this. You should heed them. Becaus you didn't, you were capable of writing code that assigns a list containing maps (each map representing one returned db result, mapping column names to the values in the row)... to a variable of type List<String>.
This model of translating a DB row to a map is a bad idea. There are plenty of nice libraries out there to interact with DBs. For example, JDBI is simple to understand has a more thought-through API for accessing results. It can even map results onto java data types.
If you must use the model you've pasted so far, for starters, add generics everywhere so that the compiler would have marked that down as a compile-time error. At the very least make that List<Map<String, Object>>.
Let me reiterate that switching things over to JDBI is a far superior road forward, but in the interests of answering the directly posed question, once you've added the generics and fixed your variable types, you can do this:
List<Map<String, Object>> data = getResultSet(syndicatorName);
for (int rowIdx = 0; rowIdx < data.size(); i++) {
Map<String, Object> row = data.get(rowIdx);
for (Map.Entry<String, Object> cell : row.entrySet()) {
System.out.printf("Row %d cell %s: %s\n", rowIdx, cell.getKey(), cell.getValue());
}
}
Note that your cell values are 'Object' here. You'd have to cast them to what you know the data type to be. This is not idiomatic java but there's no way to fix that without completely redesigning the getResultSet method. Again.. JDBI or similar libraries is what you really want here.
You need a nested Loop (at least i would do it that way...there are not only a few other ways):
for (HashMap<T,T> i : ArrayList<HashMap<T,T>>) {
for (T j : i.keySet()){
i.get(j);
//further code
}
}

How to convert a list of objects to a multi-dimensional array

I have a list of objects (result from a select query), I want to convert it into an array and I want to put each column of the query in a column in the array. I have tried many solutions in the forum but I haven't found a solution.
In my bean I have the following list:
private List<PhBonCmd> listEntree; // The PhBonCmd is an object model imported has attributes like codeprod , quant ,...
.....
String sql ="select c.codeprod as codeprod , c.quant as quant ,c.date_cmd as date_cmd, c.date_expir as date_expir,c.numbco as numbco, c.auteur as auteur,"
+"c.idcmd as idcmd ,f.nomfourn as nomfourn ,coalesce(c.quant_livre, 0) as quant_livre ,m.libelle as libelle "
+"from commandes c,listeproduit m,fournisseur f "
+"where c.codeprod=m.codeproduit and c.fourn=f.idfourn and c.statut='IN' and c.numbco ='"+getNumbco()+"' ";
listEntree = (List<PhBonCmd>) this.bcService.execRequete(sql);//Here the results of the sql query
Now what I want is to put each column of the List (listEntree) in a multidimensional arraylist, so as if I want to access to a specific single value in of the arraylist, I do so.
I want to put the results of the query in an array and from there , i want to access to elements of the array . Have things like this array1[row][col]
Why are you casting to List<PhBonCmd>? . The ResultSet is by default multidimensional. If you want to convert to a multidimensional List, you can do it by processing the ResultSet.
If you are using Spring , you can use RowMapper or ResultSetExtractor to get the desired behaviour.
I don't know the reason of doing that, when you have OOP power, but here it is.
You have to use reflection to get know fields (lets say columns if you wish) of PhBonCmd on fly:
Class clazz = PhBonCmd.class;
Field[] fields = clazz.getFields();
String[][] myDemensionalArray = new String[fields.length()][listEntree.size()];
for(int i=0; i < fields.length(); i++){
for(int j=0; j < listEntree.size(); j++){
myDemensionalArray[i][j] = fields[i].get(listEntree.get(j));
}
}

Get individual values from an array created from a resultset in java

I have an array that was created from an ArrayList which was in turn created from a ResultSet. This array contains rows of database table and each row (with several columns based on my query) exists as a single element in the array. So far so good. My problem is how to get individual values (columns) from each row which, I said earlier, now exists as an element. I can get each element (row, of course) but that is not what I want. Each element is a composite of several values and how to get those? I am a beginner and really stuck here. I think this all make sense. Here's the code how I created the array.
List resultsetRowValues = new ArrayList();
while (resultSet.next()){
for (int i = 1; i <= columnCount; i++) {
resultsetRowValues.add(resultSet.getString(i));
}
}
String[] databaseRows = (String[]) resultsetRowValues.toArray(new String[resultsetRowValues.size()]);
EDIT: More explanation
My MySQL query is as follows:
String query = "SELECT FIRSTNAME, LASTNAME, ADDRESS FROM SOMETABLE WHERE CITY='SOMECITY'";
This returns several rows in a ResultSet. And according to the sample query each element of an array will cotain three values (columns) i.e FIRSTNAME, LASTNAME and ADDRESS. But these three values exist in the array as a single element. While I want each column separately from each element (which is actually a row of the database table). When I iterate through the aarray using for loop and print the values to the console, I get output similar to the following:
Doe
Jhon
Some Street (End of First element)
Smith
Jhon
Some Apartment (End of Second element and so on)
As it is evident from the output, each element of the contains three values which are printed on separate lines.
How to get these individual values.
You probably want something like that:
List<Map<String, String>> data = new ArrayList<>();
while (resultSet.next()){
Map<String, String> map = new HashMap<>();
for (int i = 1; i <= columnCount; i++) {
map.put("column" + i, resultSet.getString(i));
}
data.add(map)
}
// usage: data.get(2).get("column12") returns line 3 / column 12
Note that there are other possible options (2D-array, guava Table, ...)

Dynamic Query Object

I am using JAVA with sql I want to create query object name dynamically based on loop
example
Query query1;
Query query2;
Query query3....
the number 1,2,3 comes from variable i incremented in for loop.
You will probably want to use a Map<String, Query> where you can then do:
Map<String, Query> queries = new HashMap<String, Query>();
for (int i = 0; i < limit; i++) {
queries.put("query" + i, new Query());
}
I'd just like to point out that this is a code smell, and you should probably wonder why you need to create so many queries.

How we get the List objects in backward direction?

Hi i am getting List object that contains pojo class objects of the table. in my case i have to show the table data in reverse order. mean that, for ex
i am adding some rows to particular table in database when i am added recently, the data is storing at last row in table(in database). here i have to show whole content of the table in my jsp page in reverse order, mean that what i inserted recently have to display first row in my jsp page.
here my code was like,
List lst = tabledate.getAllData();//return List<Table> Object
Iterator it = lst.iterator();
MyTable mt = new MyTable();//pojo class
while(it.hasNext())
{
mt=(MyTable)it.next();
//getting data from getters.
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
}
Use a ListIterator to iterate through the list using hasPrevious() and previous():
ListIterator it = lst.listIterator(lst.size());
while(it.hasPrevious()) {
System.out.println(it.previous());
}
You cannot use an iterator in this case. You will need to use index based access:
int size = lst.size();
for (int i=size - 1; i >= 0; i --)
{
MyTable mt = (MyTable)lst.get(i);
....
}
Btw: there is no need to create a new MyTable() before the loop. This is an instance that will be thrown away immediately and serves no purpose.

Categories