JDBC两种查询方法

阅读更多
//查询方法 返回值是以list形式返回的
public static List> executeQuery(String sql){
List> list = new ArrayList>();
ResultSet rs = null;
Connection conn = null;
PreparedStatement stm = null;
try{
conn = getConnection();
stm = conn.prepareStatement(sql);
rs = stm.executeQuery();
ResultSetMetaData metaData = rs.getMetaData(); 
            String[] names = new String[metaData.getColumnCount()]; 
            for (int i = 0; i < metaData.getColumnCount(); i++) { 
                names[i] = (metaData.getColumnLabel(i + 1)).toLowerCase(); 
            } 
            String str = "";
            HashMap tmp = new HashMap(); 
            while (rs.next()) { 
                tmp = new HashMap(); 
                for (int i = 0; i < names.length; i++) { 
                    str = rs.getString(i + 1); 
                    str = str == null ? "" : str.trim(); 
                    tmp.put(names[i], str); 
                } 
                list.add(tmp); 
            } 
            return list; 
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(rs != null)
rs.close();
if(conn != null)
conn.close();
if(stm != null)
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}

//更新,删除,新增方法
public static boolean updateQuery(String sql){
int effectRowNum = 0;
Connection conn = null;
PreparedStatement stm = null;
try{
conn = getConnection();
stm = conn.prepareStatement(sql);
effectRowNum = stm.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(conn != null)
conn.close();
if(stm != null)
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return effectRowNum == 1;
}

public static List execute(String sql, Class cla){
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
List ret = new ArrayList();
Field[] fields = cla.getDeclaredFields();
try{
conn = getConnection();
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
ResultSetMetaData metaDate = rs.getMetaData();
int colCount = metaDate.getColumnCount();
while(rs.next()){
Object newInstance = cla.newInstance();
for(int i = 1; i <= colCount; i++){
Object value = rs.getObject(i);
if(value != null)
for(int j = 0; j < fields.length; j++){
                        Field f = fields[j];
                        if(f.getName().equalsIgnoreCase(metaDate.getColumnName(i))){
                        Class[] paraTypes = new Class[]{value.getClass()};
                        Method method = cla.getMethod("set" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1), paraTypes);
                        method.invoke(newInstance, new Object[]{value});
                        break;
                        }
}
}
ret.add(newInstance);
}
return ret;
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(rs != null)
rs.close();
if(conn != null)
conn.close();
if(pst != null)
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}

你可能感兴趣的:(resultset,list)