将任意查询结果ResultSet转化成List<Map>(四)

2014-11-24 11:59:52 · 作者: · 浏览: 180
若不够长度,则含position后的全部记录
* @param isScrollSenstive 指定结果集是否敏感
* @return
* 获取查询结果集转化成List对象,每一条记录映射成一个HashMap对象,这个HashMap对象的键名是表中的字段名,或是字段的别名,键值为字段值,键值的类型是字段所对应的JDBC
* API的Java类。若无记录则返回零长度List对象。
* @throws SQLException
*/
public List query(String sqlquery, int position, int length, boolean isScrollSenstive) throws SQLException {
List records = new ArrayList();
try {
java.sql.DatabaseMetaData dmd = con.getMetaData();
if (dmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE)
|| dmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE)) {
if (isScrollSenstive) {
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
} else {
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
}
rs = stmt.executeQuery(sqlquery);
rsmd = rs.getMetaData();
int fieldCount = rsmd.getColumnCount();
rs.last();
int x = rs.getRow();
if (position < 1 || position > x) {
return records; //起始位置越界,则返回0条记录;
}
if (position + length > x) {
length = x - (position - 1); //若起始位置后的记录数小于length,则取起始位置后的全部记录;
}
Map valueMap = null;
if (rs.absolute(position)) {
for (int k = position; k < position + length; k++) {
valueMap = new HashMap();
for (int i = 1; i <= fieldCount; i++) {
String fieldClassName = rsmd.getColumnClassName(i);
String fieldName = rsmd.getColumnName(i);
this._recordMappingToMap(fieldClassName, fieldName, rs, valueMap);
}
records.add(valueMap);
if (!rs.next()) {
break;
}
}
}
} finally {
stmt.close();
}
return records;
}
public List query(String sqlquery, int timeout) throws SQLException源代码
[java]
/**
* 查询方法
*
* @param sqlquery 是标准查询语句,可以是任意复杂的多表查询语句,但必须是受JDBC API支持的标准查询语句
* @param timeout 设定查询时限,单位:秒;timeout=0,则查询不受时间限制
* @return 将查询结果ResultSet对象转换成List>类型的结果
* @throws SQLException
*/
public List query(String sqlquery, int timeout) throws SQLException {
List records = new ArrayList();
try {
stmt = con.createStatement();
if (timeout > 0) {
stmt.setQueryTimeout(timeout);
}
rs = stmt.executeQuery(sqlquery);
rsmd = rs.getMetaData();
int fieldCount = rsmd.getColumnCount();
while (rs.next()) {
Map valueMap = new LinkedHashMap();
for (int i = 1; i <= fieldCount; i++) {
String fieldClassName = rsmd.getColumnClassName(i);
String fieldName = rsmd.getColumnName(i);
this._recordMappingToMap(fieldClassName, fieldName, rs, valueMap);
}
records.add(valueMap);
}
rs.close();
} finally {
stmt.close();
}
db.setLastQuerySql(sqlquery);
return records;
}
public List query(String sqlquery) throws SQLException 源代码
[java]
/**
* 查询方法
*
* @param sqlquery 是标准查询语句,可以是任意复杂的多表查询语句,但必须是受JDBC API支持的标准查询语句
* @return 将查询结果ResultSet对象转换成List>