如何保存ArrayList< HashMap< String,String>>从返回功能? [英] How to save the ArrayList<HashMap<String, String>> from return function?
问题描述
我对操纵ArrayList<HashMap<String, String>>
不太熟悉.在此问题中,我想保存一个函数的返回值ArrayList<HashMap<String, String>>
.但是,如果编码错误,我也不知道天气.谁能帮我吗?
I'm not so familiar with manipulating ArrayList<HashMap<String, String>>
. In this problem I want to save the return ArrayList<HashMap<String, String>>
from a function. However, I don't know weather if I code it wrong. Can anyone help me?
我已经检查了我的sql代码,它工作得很好,并返回了我想要的东西.
I've check my sql code, it work pretty fine and return the things that I want.
List<HashMap<String, String>> ErrorList= new ArrayList<HashMap<String, String>>();
ErrorList = select("SELECT * FROM process_result WHERE (status = 'Error') AND (mailBefore = 'No');");
public List<HashMap<String, String>> select(String query) {
List<HashMap<String, String>> output = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = null;
Statement statement = null;
try {
statement = this.conn.createStatement();
ResultSet rs = statement.executeQuery(StringEscapeUtils.unescapeJava(query));
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
map = new HashMap<String, String>();
while (rs.next()) {
for (int i = 1; i <= columnCount; i++ ) {
map.put(rsmd.getColumnName(i), rs.getString(i));
}
output.add(map);
}
} catch (SQLException e) {
logger.error(e);
e.printStackTrace();
}
//System.out.print("This is select output:" + output);
return output;
}
代码没有正确保存选择函数的返回值.
The code don't correctly save the return value from select function.
推荐答案
对于同一map
实例中的每一行,您一直都用相同的列名和数据覆盖map
的键,因此您将一直最后以map
中ResultSet
中最后一行的数据为准,并且output
列表将只有一个条目
You are overwriting the keys of the map
with same column name and data for each row in the same map
instance all the time, so you would end up with the data of the last row from the ResultSet
in the map
and the output
list will have only one entry
相反,为ResultSet
中的每一行创建一个新的HashMap
实例,并将map
添加到每一行的列表中:
Instead create a new HashMap
instance for every row in the ResultSet
and add the map
to the list for each row:
while (rs.next()) {
map = new HashMap<>(); //create one new map for every row
for (int i = 1; i <= columnCount; i++ ) {
map.put(rsmd.getColumnName(i), rs.getString(i));
}
output.add(map);
}
我还建议将方法的签名更改为:
Also I suggest changing the signature of the method to:
public List<Map<String, String>> select(String query)
因此,您不要将代码耦合到实现.
So you do not couple your code to an implementation.
您还需要更改以下几行:
You would need to change these lines as well:
List<Map<String, String>> output = new ArrayList<Map<String, String>>();
// do not have a dependency on a particular implementation of the Map API
Map<String, String> map = null;
这篇关于如何保存ArrayList< HashMap< String,String>>从返回功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!