根据SQL查询返回一个List对象方法

/**
* 根据SQL查询返回一个List对象

* @param Sql

* @return

*/
public static List getListBySQL(String Sql){
ResultSet rs = null;
PreparedStatement ps = null;
Connection conn = null;
List list = new ArrayList();

try {
conn = DBConnectionFactory.getInstance().getConnection();// 获得数据库连接
ps = conn.prepareStatement(Sql);
rs = ps.executeQuery();

if (rs == null) return Collections.EMPTY_LIST;

ResultSetMetaData rsmd = rs.getMetaData(); // 得到结果集(rs)的结构信息,比如字段数、字段名等
int columnCount = rsmd.getColumnCount(); // 返回此 ResultSet 对象中的列数

while (rs.next()){
Map rowData = new HashMap();
for (int i = 1; i <= columnCount; i++) {
rowData.put(rsmd.getColumnName(i), rs.getObject(i)); // 循环列,将列数据放入到map对象中去
}
list.add(rowData);// 循环行数,将每一行的数据添加到list对象中去
}
} catch (SQLException sqle) {
log.error("根据SQL查询出现异常",sqle);
}finally{
DBConnectionPool.freeConnection(rs, ps, conn);// 释放指定的数据库访问对象资源
}
return list;
}



/**
* 测试返回的List值
* @param sql
* @throws SQLException
* 从list中取出值
*/
public void testReturnList(String sql) throws SQLException{
List resultList = getListBySQL(sql);
Iterator it = resultList.iterator();
while(it.hasNext()) {
Map values = (Map)it.next();
System.out.println(values.get("字段名"));
}
}

你可能感兴趣的:(数据库)