方法:
public List> query(String sql, Object[] parameters)
throws Exception {
List List = new ArrayList();
Connection conn = DBUtil.getConnect();
PreparedStatement pstmt = conn.prepareStatement(sql);
for (int i = 0; i < parameters.length; i++) {
// pstmt.setObject(第几个参数, 替换成什么);
pstmt.setObject(i + 1, parameters[i]);// 填充sql 语句
}
// 获取结果集
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData md = rs.getMetaData();
// 之后将获取的每一条记录封装到一个类中
int columnCount = md.getColumnCount();
//判断resultset是否为空
if (rs.wasNull() == false) {
System.out.println(rs.wasNull());
while (rs.next()) {
Map map = new HashMap();
for (int i = 1; i <= columnCount; i++) {
// rs.getObject(取第几个值)
map.put(md.getColumnName(i), rs.getObject(i));
}
List.add(map);
}
rs.close();
pstmt.close();
conn.close();
return List;
} else {
System.out.println("ResultSet为空");
return null;
}
}
测试:
sql = "select * from user_info where id > ? order by id asc";
userList = databaseFactory.query(sql, new Object[]{2});
if(userList != null) {
for(Map<String, Object> user : userList) {
System.out.println("username=" + user.get("username"));
System.out.println("password=" + user.get("password"));
System.out.println("inquiry2 ok");
System.out.println("--------------------------------------");