2022-10-10 15:32

数据库通用查询方法封装

wanmatea

JavaEE

(563)

(0)

收藏

数据库通用查询方法封装:

public static List<Object> executeQueryList(String sql, String className,Object... params){
    Connection conn=null;
    PreparedStatement ps=null;
    ResultSet rs=null;
    List<Object> list=new ArrayList<>();
    String url="jdbc:mysql://localhost:3306/shopdb?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn= DriverManager.getConnection(url,"root","wanmait");
        ps=conn.prepareStatement(sql);
        for(int i=0;i<params.length;i++){
            ps.setObject(i+1,params[i]);
        }
        rs=ps.executeQuery();
        //使用resultSetMetaDate获取ResultSet里面每条数据的字段名(数据库表里面的)
        ResultSetMetaData rsmd=rs.getMetaData();
        //查询结果一共有多少列,数据库表里面有多少个字段(属性)
        int count=rsmd.getColumnCount();
        String[] cols=new String[count];
        for(int i=0;i<cols.length;i++){
            cols[i]=rsmd.getColumnName(i+1);
        }
        Class clazz=Class.forName(className);
        while(rs.next()){
            Object obj=clazz.newInstance();
            Field[] fields=clazz.getDeclaredFields();
            for(Field f:fields){
                for(int i=0;i<cols.length;i++){
                    if(f.getName().equalsIgnoreCase(cols[i])){
                        f.setAccessible(true);
                        f.set(obj,rs.getObject(cols[i]));
                    }
                }
            }
            list.add(obj);
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } finally{
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return list;
}

使用:

public List<Product> findAll(){
    String sql="select * from product";
    List<Object> productList=DBHelper.executeQueryList(sql,"com.example.demo.Product");
    return (List<Product>)(List)productList;
}

此方法需要数据库字段和vo类属性一一对应,如果不对应可以使用下面的方法:

public static List<Map<String,Object>> executeQueryList(String sql, Object... params){
    List<Map<String,Object>> list=new ArrayList<>();
    Connection conn=null;
    PreparedStatement ps=null;
    ResultSet rs=null;
    String url="jdbc:mysql://localhost:3306/shop?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn= DriverManager.getConnection(url,"root","wanmait");
        ps=conn.prepareStatement(sql);
        for(int i=0;i<params.length;i++){
            ps.setObject(i+1,params[i]);
        }
        rs=ps.executeQuery();
        //使用resultSetMetaDate获取ResultSet里面每条数据的字段名(数据库表里面的)
        ResultSetMetaData rsmd=rs.getMetaData();
        //查询结果一共有多少列,数据库表里面有多少个字段(属性)
        int count=rsmd.getColumnCount();
        while(rs.next()){
            Map<String,Object> map=new HashMap<>();
            for(int i=0;i<count;i++){
                String columnName=rsmd.getColumnName(i+1);
                String columuType=rsmd.getColumnTypeName(i+1);
                if(columuType.equalsIgnoreCase("datetime")){
                    map.put(columnName,new Date(rs.getTimestamp(columnName).getTime()));
                }
                else if(columuType.equalsIgnoreCase("decimal")){
                    map.put(columnName,rs.getDouble(columnName));
                }
                else{
                    map.put(columnName,rs.getObject(columnName));
                }
            }
            list.add(map);
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally{
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return list;
}

使用:

public List<Product> findAll(){
    List<Product> productList=new ArrayList<>();
    String sql="select * from product";
    List<Map<String,Object>> list=DBHelper.executeQueryList(sql);
    for(Map<String,Object> m:list){
        Product p=new Product();
        p.setId((Integer) m.get("id"));
        p.setTitle((String)m.get("title"));
        p.setPrice((Double)m.get("price"));
        p.setInputTime((Date)m.get("input_time"));
        productList.add(p);
    }
    return productList;
}

0条评论

点击登录参与评论