public List<Map<String, String>> dbExecuteList(String sql){
List<Map<String, String>> list = new ArrayList<Map<String, String>>(); // 声明一个List接口的引用类型list
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = dbConn(); // 调用本类dbConn()方法得到对象Connection // 引用ArrayList类
Map<String, String> map = null; // 声明一个Map引用类型
stmt = conn.createStatement();
rs = stmt.executeQuery(sql); // 执行SQL语句返回ResultSet结果集对象
ResultSetMetaData remeda = rs.getMetaData(); // resuSet结果集得到ResultSetMetaData接口对象
int now = remeda.getColumnCount(); // 得到表列数
Map<String, String> mapname = new HashMap<String, String>();
// 从表的第1列开始,把所有列以HashMap<第*列,*列名>方式保存
for (int i = 1; i <= now; i++) {
String rowName = Integer.toString(i);
mapname.put(rowName, remeda.getColumnName(i));
}
list.add(mapname);// 把列名HashMap对象添加到list合集内
//把表里所有列的
while (rs.next()) {
map = new HashMap<String, String>();
for (int i = 1; i <= now; i++) {
map.put(remeda.getColumnName(i), rs.getString(i));
}
list.add(map);
}
rs.close();
stmt.close();
conn.close();
System.out.println("SQL语句: "+sql+" 执行完毕!!");
} catch (SQLException e) {
System.out.println("SQL语句: "+sql+" 执行失败!!!");
e.printStackTrace();
} catch (Exception ex) {
System.out.println("SQL语句: "+sql+" 执行失败!!!");
ex.printStackTrace();
} finally {
try {
if (!conn.isClosed()) {
conn.close();
conn = null;
}
} catch (Exception e) {
System.out.println("!conn.isClosed()失败!");
e.printStackTrace();
}
}
return list;
}
dbExecuteList
最新推荐文章于 2024-11-04 11:27:49 发布