if (sql == null || sql.trim().equals("")) {
log.info("参数sql不能为空,必须是select语句。");
throw new NullPointerException("sql参数不能为空字符串或者null。");
}
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
List l = new ArrayList();
try {
conn = DbConnection.getConn(); // 打开链接
pst = conn.prepareStatement(sql);// 开始执行sql
ResultSetMetaData rsmd = pst.getMetaData();
int columnCount = rsmd.getColumnCount();
String[] columnStr = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
columnStr[i - 1] = rsmd.getColumnName(i).toLowerCase();
}
rst = pst.executeQuery();
while (rst.next()) {
String[] tempObject = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
tempObject[i] = rst.getObject(columnStr[i]) == null ? ""
: rst.getObject(columnStr[i]).toString();
}
l.add(tempObject);
}
if (l.size() < 1)
l = null;
} catch (SQLException e) {
log.error(sql + "语句查询出错!", e);
return null;
} finally {
closeAll(rst, pst, conn);
}
return l;
}
public static Map<String,User> searchAllUser(String sql){
Map<String,User> users = new HashMap<String,User>();
User user = new User();
/**
* 这里你可以这样写
* List<User> users = new ArrayList<User>();
* rst = pst.executeQuery();
* while(rst.next()){
* User user = new User();
* user.setName(rst.getString("userName"));
* users.put(user);
* }
* return users;
*
*/
users.put("user",user);
return users;
}
public static List<User> getAllUser(){
Map<String,User> users = searchAllUser("select * from user");
List<User> allUsers = new ArrayList<User>();
for(int i = 0 ; i < users.size() ; i ++){
allUsers.add(users.get(i));
}
return allUsers;
}
public static void main(String[] args) {
//在这里取List中的值
List<User> users = getAllUser();
for(User user : users){
System.out.println(user.getName());
}
}
}
class User{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
for(Map.Entry<String, User> map : users.entrySet()){
String key = map.getKey();//当前Map中的Key
User value = map.getValue();//当前Map中的value
}