java 如何使用 JDBC 获取整行作为对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11824258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fetch entire row as array of objects with JDBC
提问by jondinham
I have to make a 'query' method for my class which accesses MySQL thru' JDBC.
我必须为我的类创建一个“查询”方法,它通过“JDBC”访问 MySQL。
The input parameter to the method is a full SQL command (with values included), so I don't know the names of columns to fetch out.
该方法的输入参数是一个完整的 SQL 命令(包含值),所以我不知道要提取的列的名称。
Some of the columns are strings, some others are integers, etc.
有些列是字符串,有些是整数,等等。
The method needs to return the value of type ArrayList<HashMap<String,Object>>
where each HashMap is 1 row, and the ArrayList contains all rows of result.
该方法需要返回ArrayList<HashMap<String,Object>>
每个HashMap为1行的类型的值,ArrayList包含结果的所有行。
I'm thinking of using ResultSet.getMetaData().getColumnCount()
to get the number of columns then fetch cell by cell out of the current row, but is this the only solution? any better ones?
我正在考虑使用ResultSet.getMetaData().getColumnCount()
来获取列数,然后从当前行中逐个单元格地获取,但这是唯一的解决方案吗?有更好的吗?
回答by jondinham
I have the example code here, just in case anybody need it. ('Con' in the code is the standard JDBC connection).
我这里有示例代码,以防万一有人需要它。(代码中的'Con'是标准的JDBC连接)。
//query a full sql command
public static ArrayList<HashMap<String,Object>>
rawQuery(String fullCommand) {
try {
//create statement
Statement stm = null;
stm = con.createStatement();
//query
ResultSet result = null;
boolean returningRows = stm.execute(fullCommand);
if (returningRows)
result = stm.getResultSet();
else
return new ArrayList<HashMap<String,Object>>();
//get metadata
ResultSetMetaData meta = null;
meta = result.getMetaData();
//get column names
int colCount = meta.getColumnCount();
ArrayList<String> cols = new ArrayList<String>();
for (int index=1; index<=Col_Count; index++)
cols.add(meta.getColumnName(index));
//fetch out rows
ArrayList<HashMap<String,Object>> rows =
new ArrayList<HashMap<String,Object>>();
while (result.next()) {
HashMap<String,Object> row = new HashMap<String,Object>();
for (String colName:cols) {
Object val = Result.getObject(colName);
row.put(colName,val);
}
rows.add(row);
}
//close statement
stm.close();
//pass back rows
return tows;
}
catch (Exception ex) {
System.out.print(ex.getMessage());
return new ArrayList<HashMap<String,Object>>();
}
}//raw_query