protected List<Map<String, Object>> doQuery(String sql) throws Exception {
logger.debug("method:doQuery----START");
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
// 关闭连接flag
boolean colseFlag = false;
// 打开DB链接
if (this.connection == null) {
this.connection = this.getDbConnection();
colseFlag = true;
}
PreparedStatement preStat = null;
if (this.connection != null) {
try {
preStat = this.connection.prepareStatement(sql);
// 查询一个结果集
ResultSet rs = null;
Map<String, Object> map = null;
logger.debug("SQL:" + sql);
rs = preStat.executeQuery();
// 生成ResultSetMetaData
ResultSetMetaData rsMeta = preStat.getMetaData();
while (rs.next()) {
map = this.Result2Map(rs, rsMeta);
// 追加到list中
list.add(map);
}
} catch (Exception e) {
// 记录错误信息
logger.error(e.getMessage(), e);
throw e;
} finally {
if (preStat != null) {
try {
preStat.close();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
throw e;
} finally {
preStat = null;
}
}
// 关闭数据库连接
if (colseFlag) {
this.closeDbConnection(this.connection);
}
}
} else {
throw new Exception("DB链接未取到.");
}
logger.debug("method:doQuery----END");
return list;
}
private Map<String, Object> Result2Map(ResultSet rs, ResultSetMetaData meta) throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 1; i <= meta.getColumnCount(); i++) {
map.put(meta.getColumnName(i), rs.getObject(meta.getColumnName(i)));
}
return map;
}