java jdbc连接池化封装

/////////jdbc连接操作

private static String url;

/**

* 用户名

*/

private static String userName;

/**

* 密码

*/

private static String password;

private static String driver;

// 连接池

private static int max = 20;

private static int min = 2;

private static int count = 0;

private static List<Connection> freeConn = new ArrayList<Connection>();

// private static List<Connection> useConn = new ArrayList<Connection>();

/**

* 装载驱动

*/

static {

DbConfig config = new DbConfig();

url = config.getUrl();

userName = config.getUserName();

password = config.getPassword();

driver = config.getDriver();

try {

Class.forName(driver);

} catch (ClassNotFoundException e) {

throw new ExceptionInInitializerError(e);

}

initCon();

}

public static void initCon() {

try {

// 初始化

Connection conn;

if (count > max) {// 如果大于 最大,就只new一个;

conn = DriverManager.getConnection(url, userName, password);

freeConn.add(conn);

} else {

for (int i = 0; i < min; i++) {

conn = DriverManager.getConnection(url, userName, password);

freeConn.add(conn);

count++;

}

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

* 建立数据库连接

* @return

* @throws SQLException

*/

public static synchronized Connection getConnection() throws SQLException {

if (null == freeConn || freeConn.size() == 0) {

initCon();

}

Connection conn = freeConn.get(0);

freeConn.remove(0);

if (conn.isClosed()) {// 已关闭,去找未关闭的连接

while (true) {

conn = freeConn.get(0);

if (!conn.isClosed()) {// 未关闭

freeConn.remove(0);//如果移除完了,就重新init连接

break;

}

freeConn.remove(0);//如果移除完了,就重新init连接

if (null == freeConn || 0 == freeConn.size()) {

initCon();

}

}

}

return conn;

// conn = DriverManager.getConnection(url, userName, password);

// return conn;

}

/**

* 释放连接

* @param conn

*/

private static void freeConnection(Connection conn) {

freeConn.add(conn);

// try {

// conn.close();

// } catch (SQLException e) {

// // TODO Auto-generated catch block

// e.printStackTrace();

// }

}

/**

* 释放statement

* @param statement

*/

private static void freeStatement(Statement statement) {

try {

statement.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

* 释放resultset

* @param rs

*/

private static void freeResultSet(ResultSet rs) {

try {

rs.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

* 释放资源

* @param conn

* @param statement

* @param rs

*/

public static void free(Connection conn, Statement statement, ResultSet rs) {

if (rs != null) {

freeResultSet(rs);

}

if (statement != null) {

freeStatement(statement);

}

if (conn != null) {

freeConnection(conn);

}

}

////////////////////////////////查询操作

/**

     * 根据sql获得 obj对象集合的数据

     * @param sql

     * @param cla

     * @param paramters

     * @return

     * @throws Exception

     */

    @SuppressWarnings("rawtypes")  

    public static List<Object> queryObjs(String sql,Class cla, Object... paramters)  

            throws Exception {  

   

        ResultSet rs = null;  

        try {  

            getPreparedStatement(sql);  

   

            for (int i = 0; i < paramters.length; i++) {  

                preparedStatement.setObject(i + 1, paramters[i]);  

            }  

            rs = preparedStatement.executeQuery();  

//            ResultToListObj(ResultSet rs,Class cla)

            return ResultToListObj(rs,cla);  

            

        } catch (SQLException e) {  

            throw new SQLException(e);  

        } finally {  

            free(rs);  

        }  

    }

/** 

     * 获取PreparedStatement 

     *  

     * @param sql 

     * @throws SQLException 

     */  

    private static void getPreparedStatement(String sql) throws SQLException {  

        conn = JdbcUnits.getConnection();  

        preparedStatement = conn.prepareStatement(sql);  

    }  

/** 

     * 用于增删改 

     *  

     * @param sql 

     *            sql语句 

     * @return 影响行数 

     * @throws SQLException 

     */  

    public static int update(String sql) throws SQLException {  

   

        try {  

            getPreparedStatement(sql);  

   

            return preparedStatement.executeUpdate();  

        } catch (SQLException e) {  

            throw new SQLException(e);  

        } finally {  

            free();  

        }  

    }  

 /** 

     * 用于增删改(带参数) 

     *  

     * @param sql 

     *            sql语句 

     * @param paramters 

     *            sql语句 

     * @return 影响行数 

     * @throws SQLException 

     */  

    public static int update(String sql, Object... paramters)  

            throws SQLException {  

        try {  

            getPreparedStatement(sql);  

   

            for (int i = 0; i < paramters.length; i++) {  

                preparedStatement.setObject(i + 1, paramters[i]);  

            }  

            return preparedStatement.executeUpdate();  

        } catch (SQLException e) {  

            throw new SQLException(e);  

        } finally {  

            free();  

        }  

    }  

/**

     * 返回obj对象的数据

     * @param rs

     * @param cla

     * @return

     * @throws Exception

     */

    @SuppressWarnings({ "unchecked", "rawtypes" })  

    private static List<Object> ResultToListObj(ResultSet rs,Class cla) throws Exception {  

        List list = new ArrayList();  

        

//        Class cla = Mystudy.class; 

        //获取全部公共域的方法 

        Field[] field=cla.getDeclaredFields();//获得定义的属性

//        for(Field f:field){ 

//            System.out.println("获取全部公共域的方法:"+f.toString()); 

//        } 

        

        while (rs.next()) {  

       

            ResultSetMetaData md = rs.getMetaData();  

//            Map<String,String> map = new HashMap<String,String>();  

            Object obj = cla.newInstance();//获得类实例

            

            for (int i = 1; i <= md.getColumnCount(); i++) {  

//            System.out.println(md.getColumnType(i)+":"+md.getColumnLabel(i)+">>>>>"+rs.getObject(i));

//            int tmp = md.getColumnType(i);

            for(Field f:field){ 

//                    System.out.println(f.getName()+">>"+f.getType()); ); 

            if(f.getName().equalsIgnoreCase(md.getColumnLabel(i))){//属性与表列名相同

            if("int".equalsIgnoreCase(f.getType()+"")){

           

           PropertyDescriptor pd = new PropertyDescriptor(f.getName(), cla);

               Method wM = pd.getWriteMethod();//获得写方法

               wM.invoke(obj, stringToInt(rs.getObject(i)+""));

               

            }else if("long".equalsIgnoreCase(f.getType()+"")){

            PropertyDescriptor pd = new PropertyDescriptor(f.getName(), cla);

               Method wM = pd.getWriteMethod();//获得写方法

               wM.invoke(obj, stringToLong(rs.getObject(i)+""));

            }else{

            PropertyDescriptor pd = new PropertyDescriptor(f.getName(), cla);

               Method wM = pd.getWriteMethod();//获得写方法

               wM.invoke(obj,rs.getObject(i)+"");

            }

            break;

            }

                } 

//            map.put(md.getColumnLabel(i), rs.getObject(i)+""); 

            }  

            

            list.add(obj);  

        }  

        

        return list;  

    }

/////////////////////////////////用户查询示例

public Video getVideoObjByid(int video_id) {

StringBuffer sql = new StringBuffer();

sql.append(" select * from video ");

sql.append(" where id = ? ");

sql.append(" limit 1 ");

try {

List<Object> objList = JdbcHelper.queryObjs(sql.toString(), Video.class, video_id);

Video o = null;

if (null != objList && objList.size() > 0) {

o = (Video) objList.get(0);

}

return o;

} catch (Exception e) {

e.printStackTrace();

return null;

}

}

猜你喜欢

转载自mr-lili-1986-163-com.iteye.com/blog/2367594
今日推荐