封装数据库查询方法

本文介绍了为解决数据库查询代码冗余和效率问题,所进行的数据库查询方法的封装。包括连接数据库的接口定义,以及针对Oracle和Mysql两种数据库的具体实现类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于数据繁琐的各式各样的查询语句,每次都要写上一大段查询代码,不仅造成代码冗余,而且还浪费时间。下面给出自己写的一个数据库查询方法封装:

public class AllSelect {
    public static List<Object> Select(String sql,String className) throws Exception{
        //连接数据库
        Connection conn = new MyConnection().getConnection();//后面有封装连接数据库的方法
        //预处理
        Statement st = conn.createStatement();
        //执行sql语句,并把sql查询结果存储在resultSet中
        ResultSet rs = st.executeQuery(sql);
        //使用resultSetMetaDate获取ResultSet里面每条数据的字段名(数据库表里面的)
        ResultSetMetaData rsmd = rs.getMetaData();
        //查询结果一共有多少列,数据库表里面有多少个字段(属性)
        int count = rsmd.getColumnCount();
        //创建一个数组来存放结果集中所有的字段名(把每个字段存进数组里面)
        String[] cols = new String[count];
        //循环获取所有的字段名()
        for(int i = 0;i < cols.length;i ++){
            //把resultSetMetaDate获取的字段存进数组
            cols[i] = rsmd.getColumnName(i+1);
        }
        //创建一个Arraylist存放解析出来的对象
        List<Object> list = new ArrayList<Object>();
        //获取类的反射,通过包名.类名。开始连接po层的类
        Class clss = Class.forName(className);
        while(rs.next()){
            //每次通过反射创建一个对象
            Object obj = clss.newInstance();
            //通过反射获取对象所有的属性,
            Field[] fie = clss.getDeclaredFields();
            //遍历这个对象的所有属性,把数据库查询出来的数据放入类对象中
            for(Field field:fie){
                //判断·属性的类型,每种类型对应不同的获取属性方法
                if(field.getType().getName().equals("java.lang.Integer")||
                        field.getType().getName().equals("int")){
                    //循环列名数组,找到属性名重名的列,获取这一列的值,给该属性赋值
                    for(int i = 0;i < cols.length;i ++){
                        //如果找到这一列
                        if(cols[i].equalsIgnoreCase(field.getName())){
                            //暴力访问
                            field.setAccessible(true);
                            //把表中查询出来的这一列的值给同名类的同名Int属性
                            field.set(obj, rs.getInt(cols[i]));
                        }
                    }
                }else if(field.getType().getName().equalsIgnoreCase("java.lang.String")){
                    for(int i = 0;i < cols.length;i ++){
                        if(cols[i].equalsIgnoreCase(field.getName())){
                            //暴力访问
                            field.setAccessible(true);
                            //用这一列的值给同名的String属性
                            field.set(obj, rs.getString(cols[i]));
                        }
                    }
                }else if(field.getType().getName().equalsIgnoreCase("java.sql.Date")){
                    for(int i = 0;i < cols.length;i ++){
                        if(cols[i].equalsIgnoreCase(field.getName())){
                            //暴力访问
                            field.setAccessible(true);
                            //用这一列的值给同名的Date属性
                            field.set(obj, rs.getDate(cols[i]));
                        }
                    }
                }else if(field.getType().getName().equalsIgnoreCase("java.lang.Double")||
                        field.getType().getName().equalsIgnoreCase("double")){
                    //循环列名数组,找到属性名重名的列,获取这一列的值,给该属性赋值
                    for(int i = 0;i < cols.length;i ++){
                        //如果找到这一列
                        if(cols[i].equalsIgnoreCase(field.getName())){
                            //暴力访问
                            field.setAccessible(true);
                            //用这一列的值给同名的Double属性
                            field.set(obj, rs.getDouble(cols[i]));
                        }
                    }
                }
            }
            list.add(obj);
        }
        rs.close();
        st.close();
        conn.close();
        return list;
    }
}

连接数据库的封装方法:
连接数据库接口:

public interface DBConnection {

    public Connection getConnection();
    public void close();
}

连接数据库实现类(Oracle数据库):

public class MyConnection implements DBConnection{
    Connection conn;
    @Override
    public Connection getConnection() {
        // TODO Auto-generated method stub
        String Driver="oracle.jdbc.driver.OracleDriver";    //连接数据库的方法  
        String URL="jdbc:oracle:thin:@localhost:1521:benxi";    //benxi为数据库的SID  
        String Username="scott";    //用户名  
        String Password="123456";    //密码  
        try {
            Class.forName(Driver) ;
            conn=DriverManager.getConnection(URL,Username,Password);      
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }    //加载数据库驱动  

        return conn;
    }

    @Override
    public void close() {
        // TODO Auto-generated method stub
        try {
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

连接数据库实现类(Mysql):

public class MysqlConnection implements DBConnection{
    public static final String DRIVECLASS="com.mysql.jdbc.Driver";
    public static final String URL="jdbc:mysql://localhost:3306/test01";
    public static final String UNAME="root";
    public static final String PASS="123456";
    static{
        try {
            Class.forName(DRIVECLASS);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 获得连接
     */
    Connection conn  = null;
    public Connection getConnection() {
        try {
            conn = DriverManager.getConnection(URL,UNAME,PASS);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 关闭连接
     */

    @Override
    public void close() {
        // TODO Auto-generated method stub
        try {
            if(conn!=null&&!conn.isClosed()){
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值