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, ...)
Related
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));
}
}
I'm fairly new to Java and have been searching everywhere for an answer.
I run a sql query and use the response to build a list of hashmaps from the column name and values.
List<HashMap<String,String>> rulesList = Sql.getStuff("abc");
This gets me a list like this {column_1=abc, column_3=ghi, column_2=def}
I want to do two things with this list. First off I want to see if any column contains a particular value (ruleName). This part decent enough.
if (rulesList.get(0).containsValue(ruleName)) {
System.out.println("Expected: " + ruleName);
System.out.println("Actual: " + ruleName); //Would like to change this to include the actual column name and result
Then I want to check all the other columns that have a particular phrase in their name to see if they contain a value or not, such as the word "column" from "column_1, column_2, column_3". If they do contain the value then I want to print out the column name and value.
However, this is when I run into the problem of not knowing how to select from within the list. How can I get only column_2 and its accompanying data, or the column name associated with value abc?
something like this example?
List<HashMap<String,String>> rulesList = new ArrayList<HashMap<String,String>>() {{
for (int i = 0; i < 4; i++) {
HashMap<String,String> map = new HashMap<>();
map.put("key", Integer.toString(i));
map.put("column1", "Value in Column1 in row " + i);
map.put("column2", "Value in Column2 in row " + i);
add(map);
}
}};
for (HashMap<String,String> row : rulesList) {
for (String columnName : row.keySet()) {
// look for a column name
if(columnName.contains("column")) {
System.out.printf("Column \"%s\" has a value of \"%s\"%n", columnName, row.get(columnName));
}
// look for a cell value
if(row.get(columnName).matches(".+Column\\d in row 1")) {
System.out.printf("Value found in %s, row %s%n", columnName, row.get("key"));
}
}
}
I think you just need vocabulary : a hashmap associates a key (unique) with one value.
So with that keywords in mind you can easily find answer, like :
First off I want to see if any column contains a particular value (ruleName)
Here is an example
Then I want to check all the other columns that have a particular phrase in their name to see if ...
And there.
your question is premised around a list of hashmaps
Based on your question, it looks like you might be trying to use this structure:
List_Row<HashMap<String_ColumnName, String_Value>>
If this is the case, consider modifying your storage structure and storing a hashmap each with a list:
HashMap_ColumnName<ArrayList<String_Values>>
then you can simply grab a column and look through data. to get the row back as a list, you can write a function to do that pretty easily
getRow(i) {
HashMap<String,String> row = new HashMap<String,String>()
for(k:results) {
row.put(k, results.get(k).get(i))
}
return row
}
I have a List of Strings which contains search items for multiple attributes in an Entity. I would like to Query the database and retrieve any Entity which has one of these Strings in any one of the specified attributes. For instance, say I have a List of partial names:
//contents of the list (for visual purposes)
["Mi", "Chr", "Leo", "Jo", "Par"]
Also, let us assume that we do not know the size of the list. Now, say I have an Entity with the following attributes:
String firstName;
String lastName;
How can I retrieve (preferably in one Query) all Entities whose first OR last names contain any of the Strings within the list?
Something like (Pseudo code):
SELECT u FROM User u WHERE u.firstName LIKE (%Mi% OR %Chr% OR %Leo% OR %Jo% OR %Par%)
OR u.lastName LIKE (%Mi% OR %Chr% OR %Leo% OR %Jo% OR %Par%)
If there were something like a LIKE IN clause that'd be perfect but, unfortunately, I don't believe JPQL supports that. So, how could this be done?
This code builds a query using the IN condition.
String query = "";
String whereClause = "";
for(int i = 0; i < LIST.size(); i++) {
// using * wildcard
whereClause += "\"*" + LIST.get(i).toString() + "*\",";
}
query = String.format("SELECT User.firstName, User.lastName FROM User WHERE User.firstName IN (%s) OR User.lastName IN (%s);", whereClause, whereClause);
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
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.