public class DAOImpl implements DAOInter {
private Connection conn;// 获取数据库连接
@Override
public List<Map<String, String>> selectEntity(String sql, Object[] objects, String[] items) {
conn = SQLconnection.getConnection();
List<Map<String, String>> list = null;// 声明一个List集合来存放查询到的结果
try {
PreparedStatement pst = conn.prepareStatement(sql);
if (objects != null) {// 如果包含条件
for (int i = 0; i < objects.length; i++) {
pst.setObject(i + 1, objects[i]);// 将条件添加到PreparedStatement中
}
}
ResultSet rst = pst.executeQuery();// 查询结果并存放在结果集中
list = new ArrayList<Map<String, String>>();// 实例化集合对象
Map<String, String> map;// 实例化一个Map对象存放查询到的一条数据
while (rst.next()) {
map = new HashMap<String, String>();
for (int i = 0; i < items.length; i++) {
// key--列名,value--该列的值
//重写将Object转换为String的方法以防止Object为null时报错
map.put(items[i], Rules.objectToString(rst.getObject(items[i])));
}
list.add(map);//将获得的一条数据放进list集合
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SQLconnection.closeConnection(conn);
}
return list;
}
@Override
public int changeEntity(String sql, Object[] objects) {
conn = SQLconnection.getConnection();
int result = -1;
try {
PreparedStatement pst = conn.prepareStatement(sql);
if (objects != null) {
for (int i = 0; i < objects.length; i++) {
// 对每一个sql语句中使用的参数赋值,顺序一一对应
pst.setObject(i + 1, objects[i]);
}
}
result = pst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SQLconnection.closeConnection(conn);
}
return result;
}}