jdbc模拟hibernate-list

收集别人的资料加修改

连接

View Code
public Connection getConn() throws SQLException {
        MysqlDataSource ds = new MysqlDataSource();
        ds.setUrl("jdbc:mysql://localhost:3306/test?user=root&password=1");
        return (Connection) ds.getConnection();
    }

 

主要代码

View Code
/**
     * 查询返回List集合
     * 
     * @param className
     *            类名.class
     * @return
     */
    public List<?> list(Class<?> className) {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        // 数组来处理
        List<Object> arr = new ArrayList<Object>();
        try {
            String sql = "select * from " + getEntityName(className);
            // 构造返回的结果集
            Object resultValueType = "";
            con = this.getConn(); // 取得数据库连接
            pstmt = (PreparedStatement) con.prepareStatement(sql);
            rs = (ResultSet) pstmt.executeQuery(); // 执行查询
            // 是以ResultSetMetaData对象 , 取得数据表中的字段数目,类型等返回结果
            ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
            // 列的总数
            int colCount = rsmd.getColumnCount();
            while (rs.next()) {
                // 根据类名实例化对象
                Object obj = className.newInstance();
                for (int i = 1; i <= colCount; i++) {
                    // 列名不为空
                    if (rs.getString(rsmd.getColumnName(i)) != null)
                        resultValueType = rs.getObject(rsmd.getColumnName(i));
                    // 通过反射获取对象set方法
                    Method m = obj.getClass().getMethod(
                            getSetMethodName(rsmd.getColumnName(i)),
                            new Class[] { resultValueType.getClass() });
                    // 给对象赋值
                    m.invoke(obj, new Object[] { resultValueType });
                }
                arr.add(obj);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } finally {
            this.colseAll(con, pstmt, rs);
        }
        return arr;
    }

不断改进,希望有更好的写法

posted @ 2013-05-04 21:28  肥仔-酷(code)  阅读(151)  评论(1)    收藏  举报