使用JDBC连接数据库,查询结果转成List或者Map(臃肿版)

/**

* 把查询的结果转换成List

* @param  rs

* @return  list

*/

protected List<Map<String, Object>> fullToList(ResultSet rs) {

ArrayList list = new ArrayList();

try {

int iColumn = rs.getMetaData().getColumnCount();

while (rs.next()) {

Map<String, Object> map = new LinkedHashMap<String, Object>();

for (int i = 1; i <= iColumn; i++) {

String tmpkey = rs.getMetaData().getColumnName(i);// 通过索引找到行的名字


String[] tmps = tmpkey.split("_");// 分割所有含"_"字符,返回数组

String key = "";

for (int j = 0; j < tmps.length; j++) {

if (j == 0) {

key += tmps[j].toLowerCase();// 转换为小写

} else {

key += tmps[j].substring(0, 1).toUpperCase() + tmps[j].substring(1).toLowerCase();

}

}


Object val = null;

// switch行类型

switch (rs.getMetaData().getColumnType(i)) {

case Types.DATE:

val = rs.getDate(i);

break;

case Types.DOUBLE:

if (rs.getObject(i) == null)

val = null;

else

val = rs.getDouble(i);

break;

case Types.NUMERIC:

if (rs.getObject(i) == null)

val = null;

else

val = rs.getDouble(i);

break;

case Types.DECIMAL:

if (rs.getObject(i) == null)

val = null;

else

val = rs.getDouble(i);

break;

case Types.INTEGER:

if (rs.getObject(i) == null)

val = null;

else

val = rs.getInt(i);

break;

default:

val = rs.getString(i);

break;

}


if (null != val) {

// map找找不到指定键便设置个

if (!map.containsKey(key)) {

map.put(key, val);

}

}

}

list.add(map);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (rs != null)

rs.close();

rs = null;

} catch (SQLException e) {

e.printStackTrace();

}

}

return list;

}


/**

* 把查询的结果转换成Map

* @param  rs

* @return  map

*/

protected Map<String, Object> fullToMap(ResultSet rs) {

Map<String, Object> map = new TreeMap<String, Object>();

try {

int iColumn = rs.getMetaData().getColumnCount();

while (rs.next()) {

for (int i = 1; i <= iColumn; i++) {

String tmpkey = rs.getMetaData().getColumnName(i);


String[] tmps = tmpkey.split("_");

String key = "";

for (int j = 0; j < tmps.length; j++) {

if (j == 0) {

key += tmps[j].toLowerCase();

} else {

key += tmps[j].substring(0, 1).toUpperCase() + tmps[j].substring(1).toLowerCase();

}

}


Object val = null;

switch (rs.getMetaData().getColumnType(i)) {

case Types.DATE:

val = rs.getDate(i);

break;

default:

val = rs.getString(i);

break;

}

if (null != val) {

if (!map.containsKey(key)) {

map.put(key, val);

}

}

}

break;

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (rs != null)

rs.close();

rs = null;

} catch (SQLException e) {

e.printStackTrace();

}

}

return map;

}


你可能感兴趣的:(使用JDBC连接数据库,查询结果转成List或者Map(臃肿版))