Loop in List of Map in get Query JDBC [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to make a get result of my query with List<Map<String, String>> result
But I'm blocked because I don't see how I can do the loop in my List Map and I have an error in method put
This is a part of my method with the loop for below :
protected List<Map<String, String>> getAllResultForQuery(String sql) throws SQLException {
List<Map<String, String>> result = null;
Connection conn = null;
Statement stmt = null;
try {
// Create connection
conn = endpoint.getDBConnection();
// Execute a query
stmt = conn.createStatement();
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(sql);
LOG.debug("Execute query: " + sql);
ResultSetMetaData rsmd = rs.getMetaData();
int nbColumns = rsmd.getColumnCount();
//loop
for (Map<String, String> map : result) {
for (Map.Entry<String, String> entry : map.entrySet()) {
if (rs.next()) {
if (result == null) {
result = new HashMap<String, String>();
}
for (int i = 1; i <= nbColumns; i++) {
String columnName = rsmd.getColumnName(i).toUpperCase();
String columnValue = rs.getString(i);
result.put(columnName, columnValue);
}
}
}
}
Anyone can Help please ?
Thanks

Try this.
protected List<Map<String, String>> getAllResultForQuery(String sql) throws SQLException {
List<Map<String, String>> result = new ArrayList<>();
try (Connection conn = endpoint.getDBConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
ResultSetMetaData rsmd = rs.getMetaData();
int nbColumns = rsmd.getColumnCount();
while (rs.next()) {
Map<String, String> map = new HashMap<>();
for (int i = 1; i <= nbColumns; i++) {
String columnName = rsmd.getColumnName(i).toUpperCase();
String columnValue = rs.getString(i);
map.put(columnName, columnValue);
}
result.add(map);
}
}
return result;
}

I make like this :
for (Map result : results) {
if (rs.next()) {
if (result == null) {
result = new HashMap<String, String>();
}
for (int i = 1; i <= nbColumns; i++) {
String columnName = rsmd.getColumnName(i).toUpperCase();
String columnValue = rs.getString(i);
result.put(columnName, columnValue);
}
}
}
How do you think ?

Related

Storing Multiple Rows from MySQL query in MultiDimensional HashMap

So I'm trying to store a MySQL query result set into a multi dimensional HashMap as listed so:
public HashMap<String, HashMap<String, String>> getData(String query)
{
Statement stmt = null;
HashMap<String, HashMap<String, String>> results = new HashMap<String, HashMap<String, String>>();
try
{
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next())
{
for (int i = 1; i < rsmd.getColumnCount() + 1; i++)
{
results.put(Integer.toString(i - 1), new HashMap<String, String>());
results.get(Integer.toString(i - 1)).put(rsmd.getColumnLabel(i), rs.getString(i));
}
}
}
catch (SQLException ex)
{
ex.printStackTrace(System.out);
}
return results;
}
However when using the function to print it out as so:
public static void printMap(Map mp)
{
Iterator it = mp.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove();
}
}
It is only storing a single row result and I can't wrap my head around why.
0 = {Date=2014-11-04}
1 = {Num=1256}
2 = {ATime=null}
3 = {ALocCode=null}
4 = {DTime=1:00 PM}
5 = {DLocCode=JFK}
6 = {EstATime=8:00 PM}
7 = {EstDTime=1:00 PM}
8 = {EId=7624}
My question is, and the only way I can put it is relating to PHP, is how can I make it store like this?
$result[0]['Date'] = '3214';
....
$result[1]['Date'] = '6426';
Since that is essentially what I'm trying to achieve?
main problem that you've swapped "rows" and "columns", next one is that you're re-creating HashMap every time you put field, proper code will look like this:
public Map<String, Map<String, String>> getData(final String query) {
final Map<String, Map<String, String>> results = new HashMap<>();
try (final Statement stmt = this.conn.createStatement(); final ResultSet rs = stmt.executeQuery(query);) {
final ResultSetMetaData rsmd = rs.getMetaData();
long rId = 0;
while (rs.next()) {
final Map<String, String> record = new HashMap<>();
for (int i = 1; i < (rsmd.getColumnCount() + 1); i++) {
record.put(rsmd.getColumnLabel(i), rs.getString(i));
}
results.put(String.valueOf(rId++), record);
}
} catch (final SQLException ex) {
ex.printStackTrace(System.out);
}
return results;
}
public static void printMap(final Map<?, ?> mp) {
for (final Entry<?, ?> entry : mp.entrySet()) {
final Object key = entry.getKey();
final Object value = entry.getValue();
if (value instanceof Map) {
System.out.println(key);
printMap((Map<?, ?>) value);
} else {
System.out.println(key + "=" + entry.getValue());
}
}
}
The answer by Lashane is good for the errors you needed solving, however it can be improved:
You wanted numeric access ($result[0]['Date']) to the rows, not string.
print method should use fully typed parameter.
Rows should be stored in TreeMap or LinkedHashMap or ArrayList to retain row order. ArrayList is better for your case, actually.
Columns should be stored in LinkedHashMap to retain column order.
Do not catch exception and continue. Allow it to cascade up to caller.
Updated version:
public List<Map<String, String>> getData(final String query) throws SQLException {
final List<Map<String, String>> results = new ArrayList<>();
try (Statement stmt = this.conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
Map<String, String> record = new LinkedHashMap<>();
for (int col = 1; col <= metaData.getColumnCount(); col++)
record.put(metaData.getColumnLabel(col), rs.getString(col));
results.add(record);
}
}
return results;
}
public static void printMap(List<Map<String, String>> rows) {
for (int rowNum = 0; rowNum < rows.size(); rowNum++)
System.out.println(rowNum + " = " + rows.get(rowNum));
}
You can now access it like you did in PHP:
// PHP (for reference, the way you requested)
$result[0]['Date']
// Java
result.get(0).get("Date")
// Groovy
result[0]['Date']
result[0].Date
// JSP
<c:forEach var="row" items="${result}" varStatus="rowStatus">
${rowStatus.index} = <c:out value="${row.Date}"/>, ...
</c:forEach>

Storing array and accessing them

This is the coding which I have used to retrieve data from the "GeneID" column. Using this coding I can print all names under the "GeneID" column. But I want to store each and every names from the column to access those name separately. Can anyone help me with this?
String name1[] = new String[100];
int i = 0;
String query = "select distinct GeneID from gene1";
PreparedStatement pest = connection.prepareStatement(query);
ResultSet rs = pest.executeQuery();
while (rs.next()) {
name1[i] = rs.getString("GeneID");
System.out.println(name1[i]);
}
rs.close();
pest.close();
For using array you have to increment i inside the while (rs.next()) {
String name1[] = new String[100];
int i = 0;
String query = "select distinct GeneID from gene1";
PreparedStatement pest = connection.prepareStatement(query);
ResultSet rs = pest.executeQuery();
while (rs.next()) {
name1[i] = rs.getString("GeneID");
System.out.println(name1[i]);
i++;
}
rs.close();
pest.close();
}
For accessing you can iterate over the array
for(int i;i<name1.length-1;i++){
System.out.println("Id is "+name1[i]);
}
Or you can use
for (String id: name1) {
System.out.println("Id is "+name1[i]);
}
You can also use ArrayList to store variable like below
ArrayList ar=new ArrayList();
String query = "select distinct GeneID from gene1";
PreparedStatement pest = connection.prepareStatement(query);
ResultSet rs = pest.executeQuery();
while (rs.next()) {
String id = rs.getString("GeneID");
ar.add(id);
}
rs.close();
pest.close();
}
For iterating over ArrayList
for (int i = 0; i < ar.size(); i++) {
System.out.println("Id is "+ar.get(i));
}
or
for (String id : ar) {
System.out.println("Id is "+ar.get(i));
}
use arrayList, so that you can use a method of .add(), this proves much helpful
List ls=new ArrayList();
ResultSet rsp=pss.executeQuery("select * from student");
while(rsp.next()){
ls.add(rsp.getString("your_column_name"));
}
rsp.close();

Get tableName values to be put into hashmap

I need to tablevalues.. into the map..
My code is bellow:
public HashMap getValuesFromDeleteAction(String tableName,Object[] filterColumn,Object[] filterValue){
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
HashMap map = new HashMap();
try{
System.out.println("====DELETE_ACTION===");
conn=this.getConnection();
if(conn!=null && !conn.isClosed()){
if(filterColumn!=null && filterValue!=null && !tableName.trim().isEmpty()
&&filterColumn.length==filterValue.length){
String sql = "SELECT * FROM "+tableName+"";
String filterSql = " WHERE " ;
for(int i=0;i<filterColumn.length;i++){
if(i==0){
filterSql = filterColumn[i]+"="+"'"+filterValue[i]+"'";
}else{
filterSql= filterSql+" AND "+filterColumn[i]+"="+"'"+filterValue[i]+"'"; }
}
String sSql=sql+filterSql;
ps = conn.prepareStatement(sSql);
rs=ps.executeQuery();
while(rs.next())
{
map.put(tableName +"LAST_UPDATE_DATE", rs.getString("LAST_UPDATE_DATE"));
map.put(tableName +"LAST_UPDATE_BY" , rs.getString("LAST_UPDATE_BY"));
}
}else{
//do nothing
}
System.out.println("MapValues==2323===>"+map);
}
}catch(Exception e){
}
return map;
}
first define your map by this:
Map<String,String> map = new HashMap<String, String>();
and where is your connection settings!?
then try this:
while(rs.next()) {
map.put("LAST_UPDATE_DATE", rs.getString("LAST_UPDATE_DATE"));
map.put("LAST_UPDATE_BY", rs.getString("LAST_UPDATE_BY"));
}

Copying Resultset content to arraylist and comparing both the values

In the below code I am copying resultset content to arraylist. First part of the wile loop i.e while(RS.next()) is returing the results but when cursor moves to
Next while loop i.e while(SR.next()) I am getting "result set is closed". Please help me where I am doing mistake.
String SSQ = "select DISTINCT S_NUMBER from OTG.S_R_VAL" +
" WHERE R_TS = (SELECT MAX(R_TS) FROM OTG.S_R_VAL) order by S_NUMBER";
String SDS = "SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN" +
"(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO )";
String SSR = "SELECT DISTINCT S_NO FROM OTG.R_VAL where S_NO != 'NULL' order by S_NO";
String SSO = "Select O_UID from OTG.OPTY where C_S_NO IN" +
"( SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO ))";
//Statement statement;
try {
connection = DatabaseConnection.getCon();
statement = connection.createStatement();
statement1 = connection.createStatement();
statement2 = connection.createStatement();
statement3 = connection.createStatement();
statement4 = connection.createStatement();
ResultSet RS = statement1.executeQuery(selectQuery);
ResultSet DS = statement2.executeQuery(Distinct_SiebelNo);
ResultSet SR = statement3.executeQuery(SiebelNo_Rev);
ResultSet SO = statement4.executeQuery(selected_OppId);
ArrayList<String> RSList = new ArrayList<String>();
ArrayList<String> SRList = new ArrayList<String>();
/* ResultSetMetaData resultSetMetaData = RS.getMetaData();
int count = resultSetMetaData.getColumnCount();*/
int count=1;
System.out.println("******count********"+count);
while(RS.next()) {
int i = 1;
count=1;
while(i < count)
{
RSList.add(RS.getString(i++));
}
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
/* ResultSetMetaData resultSetMetaData1 = SR.getMetaData();
int count1 = resultSetMetaData1.getColumnCount();*/
int count1=1;
while(SR.next()) {
int i = 1;
while(i < count1)
{
SRList.add(SR.getString(i++));
}
System.out.println(SR.getString("SIEBEL_NO"));
SRList.add( SR.getString("SIEBEL_NO"));
}SR.close();
connection.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The logic of each loop is flawed.
int count=1;//Count is being set to one
while(RS.next()) {
int i = 1;//i is being set to one
count=1;//count again set to one
while(i < count) //condition will always fail as one is never less than one
{
RSList.add(RS.getString(i++));//Code is never Reached
}
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
The second while is not needed. Just use this:
int count = 1;
while(RS.next()) {
RSList.add(RS.getString(count++));
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
EDIT
int count1=1;
while(SR.next()) {
SRList.add(SR.getString(count1++));
System.out.println(SR.getString("SIEBEL_NO"));
SRList.add( SR.getString("SIEBEL_NO"));
}
EDIT 2:
for (String s : RSList)
for(String s1 : SRList)
if (s.equals(s1))
//Do what you need
You are using the first resultset (RS) in the second loop (System.out.println line)

Efficient way to Handle ResultSet in Java

I'm using a ResultSet in Java, and am not sure how to properly close it. I'm considering using the ResultSet to construct a HashMap and then closing the ResultSet after that. Is this HashMap technique efficient, or are there more efficient ways of handling this situation? I need both keys and values, so using a HashMap seemed like a logical choice.
If using a HashMap is the most efficient method, how do I construct and use the HashMap in my code?
Here's what I've tried:
public HashMap resultSetToHashMap(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
HashMap row = new HashMap();
while (rs.next()) {
for (int i = 1; i <= columns; i++) {
row.put(md.getColumnName(i), rs.getObject(i));
}
}
return row;
}
Iterate over the ResultSet
Create a new Object for each row, to store the fields you need
Add this new object to ArrayList or Hashmap or whatever you fancy
Close the ResultSet, Statement and the DB connection
Done
EDIT: now that you have posted code, I have made a few changes to it.
public List resultSetToArrayList(ResultSet rs) throws SQLException{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
ArrayList list = new ArrayList(50);
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);
}
return list;
}
I just cleaned up RHT's answer to eliminate some warnings and thought I would share. Eclipse did most of the work:
public List<HashMap<String,Object>> convertResultSetToList(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
while (rs.next()) {
HashMap<String,Object> row = new HashMap<String, Object>(columns);
for(int i=1; i<=columns; ++i) {
row.put(md.getColumnName(i),rs.getObject(i));
}
list.add(row);
}
return list;
}
RHT pretty much has it. Or you could use a RowSetDynaClass and let someone else do all the work :)
this is my alternative solution, instead of a List of Map, i'm using a Map of List.
Tested on tables of 5000 elements, on a remote db, times are around 350ms for eiter method.
private Map<String, List<Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
Map<String, List<Object>> map = new HashMap<>(columns);
for (int i = 1; i <= columns; ++i) {
map.put(md.getColumnName(i), new ArrayList<>());
}
while (rs.next()) {
for (int i = 1; i <= columns; ++i) {
map.get(md.getColumnName(i)).add(rs.getObject(i));
}
}
return map;
}
A couple of things to enhance the other answers. First, you should never return a HashMap, which is a specific implementation. Return instead a plain old java.util.Map. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).
i improved the solutions of RHTs/Brad Ms and of Lestos answer.
i extended both solutions in leaving the state there, where it was found.
So i save the current ResultSet position and restore it after i created the maps.
The rs is the ResultSet, its a field variable and so in my solutions-snippets not visible.
I replaced the specific Map in Brad Ms solution to the gerneric Map.
public List<Map<String, Object>> resultAsListMap() throws SQLException
{
var md = rs.getMetaData();
var columns = md.getColumnCount();
var list = new ArrayList<Map<String, Object>>();
var currRowIndex = rs.getRow();
rs.beforeFirst();
while (rs.next())
{
HashMap<String, Object> row = new HashMap<String, Object>(columns);
for (int i = 1; i <= columns; ++i)
{
row.put(md.getColumnName(i), rs.getObject(i));
}
list.add(row);
}
rs.absolute(currRowIndex);
return list;
}
In Lestos solution, i optimized the code. In his code he have to lookup the Maps each iteration of that for-loop. I reduced that to only one array-acces each for-loop iteration. So the program must not seach each iteration step for that string-key.
public Map<String, List<Object>> resultAsMapList() throws SQLException
{
var md = rs.getMetaData();
var columns = md.getColumnCount();
var tmp = new ArrayList[columns];
var map = new HashMap<String, List<Object>>(columns);
var currRowIndex = rs.getRow();
rs.beforeFirst();
for (int i = 1; i <= columns; ++i)
{
tmp[i - 1] = new ArrayList<>();
map.put(md.getColumnName(i), tmp[i - 1]);
}
while (rs.next())
{
for (int i = 1; i <= columns; ++i)
{
tmp[i - 1].add(rs.getObject(i));
}
}
rs.absolute(currRowIndex);
return map;
}
Here is the code little modified that i got it from google -
List data_table = new ArrayList<>();
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(conn_url, user_id, password);
Statement stmt = con.createStatement();
System.out.println("query_string: "+query_string);
ResultSet rs = stmt.executeQuery(query_string);
ResultSetMetaData rsmd = rs.getMetaData();
int row_count = 0;
while (rs.next()) {
HashMap<String, String> data_map = new HashMap<>();
if (row_count == 240001) {
break;
}
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
data_map.put(rsmd.getColumnName(i), rs.getString(i));
}
data_table.add(data_map);
row_count = row_count + 1;
}
rs.close();
stmt.close();
con.close();
public static List<HashMap<Object, Object>> GetListOfDataFromResultSet(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int count = metaData.getColumnCount();
String[] columnName = new String[count];
List<HashMap<Object,Object>> lst=new ArrayList<>();
while(rs.next()) {
HashMap<Object,Object> map=new HashMap<>();
for (int i = 1; i <= count; i++){
columnName[i-1] = metaData.getColumnLabel(i);
map.put(columnName[i-1], rs.getObject(i));
}
lst.add(map);
}
return lst;
}

Categories