利用反射和元数据编写的通用更新和通用查询

/**
* 通用更新
* @param sql
* @param objects
* @throws IOException
*/
public void update(String sql,Object...objects) throws IOException{
Connection conn=null;
PreparedStatement prst=null;
conn=DBTool.getConnection();
try {
prst=conn.prepareStatement(sql);
for(int i=0;i<objects.length;i++){
prst.setObject(i+1,objects[i]);
}
prst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBTool.close(prst, conn);
}
}

/**
* 通用查询
* @param clazz 实体类的字节码对象
* @param sql
* @param objects:填充占位符的可变参数
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws IOException
*/

//获取结果集,再获取有多少列和列的别名
//利用列的别名获取结果集中对应列的值,别名作为键,值作为Map集合的值添加到Map集合中,在把Map集合放到List集合中,
//遍历List集合和Map集合分别获取键和值(也就是实例的属性和属性值)


public <T> T get(Class<T> clazz,String sql,Object...objects) throws InstantiationException, IllegalAccessException, InvocationTargetException, IOException{
Connection conn=null;
PreparedStatement prst=null;
ResultSet rs=null;
conn=DBTool.getConnection();
T entity=null;
try {
prst=conn.prepareStatement(sql);
for(int i=0;i<objects.length;i++){
prst.setObject(i+1, objects[i]);
}
rs=prst.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
int columnCount=rsmd.getColumnCount();
Map<String,Object> map=new HashMap<String,Object>();
if(rs.next()){
//获取结果集有多少列,及列的别名
for(int i=0;i<columnCount;i++){
String key=rsmd.getColumnLabel(i+1);
// 获取属性值
Object value=rs.getObject(i+1);
map.put(key, value);
}
if(map.size()>0){
entity=clazz.newInstance();
for(Map.Entry<String, Object> entry:map.entrySet()){
String key=entry.getKey();
Object value=entry.getValue();
BeanUtils.setProperty(entity, key, value);
}
}


}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBTool.close(rs, prst, conn);
}
return entity;
}

//还可以把获取列的别名抽取出来

private List<String> getColumnLabels(ResultSet rs) throws SQLException{
List<String> labels=new ArrayList<String>();
ResultSetMetaData rsmd=rs.getMetaData();
int columnCount=rsmd.getColumnCount();
for(int i=0;i<columnCount;i++){
String label=rsmd.getColumnLabel(i+1);
labels.add(label);
}
return labels;
}

原文地址:https://www.cnblogs.com/cn-chy-com/p/8315837.html