封装数据库查询方法

来源:互联网 发布:节奏大师没有网络可用 编辑:程序博客网 时间:2024/05/22 00:26

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

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();        }    }}
原创粉丝点击