dbcp数据库操作类的使用例子

例子1:

/**
 * 数据库操作类
 * 
 * @author Administrator
 * 
 */
public class DBUtilDBCP {
    
    private static DataSource ds;//数据源
    
    static {
        ds = getDataSource();
    }
    
    /**
     * 获取数据源
     * @return
     */
    private static DataSource getDataSource() {

        //创建数据源对象
        BasicDataSource ds = new BasicDataSource();
        //设置初始化连接数
        ds.setInitialSize(1);
        //设置最大连接数
        ds.setMaxTotal(10);
        //设置最小空闲连接数
        ds.setMinIdle(1);
        //设置最大空闲链接数  0-无限制
        ds.setMaxIdle(0);
        //设置最大等待毫秒数
        ds.setMaxWaitMillis(5000);
        //设置账户
        ds.setUsername("root");
        //设置密码
        ds.setPassword("123456");
        //设置链接路径
        ds.setUrl("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8");
        //设置驱动
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        return ds;
    }
    
    
    
    /**
     * 获取链接
     * @return 一个新链接
     */
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = ds.getConnection(); //从数据源中获取一个链接
        } catch (Exception e) {
            System.out.println("获取链接失败:"+e);
        }
        return conn;
    }
    

    /**
     * 执行增删改草主
     * @param sql sql语句
     * @param paras 参数值
     * @return 受影响行数  -1表示异常
     */
    public static int executeUpdate(String sql, Object... paras) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 链接
            conn = getConnection();
            // 指令
            ps = conn.prepareStatement(sql);
            if (paras != null)
                for (int i = 0; i < paras.length; i++) {
                    ps.setObject(i + 1, paras[i]);
                }
            // 更新
            return ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, ps, null);
        }
        return -1;
    }
    /**
     * 执行事务
     * @param sqls sql语句集合
     * @param paras sql语句中参数集合
     * @return true-成功  false-失败
     */
    public static boolean executeTransaction(List<String> sqls,List<List<Object>> paras){
        Connection conn = null;
        try {
            //链接
            conn = getConnection();
            conn.setAutoCommit(false); //不自动提交
            
            //遍历每条sql语句
            int k = 0; //防止某些sql语句没有参数
            for(int i = 0;i<sqls.size();i++){
                String sql = sqls.get(i);
                //指令
                PreparedStatement ps = conn.prepareStatement(sql);
                //执行的sql语句有参数
                if(sql.indexOf("?") != -1 ){
                    //为sql中参数参数赋值
                    List<Object> list = paras.get(k);
                    
                    for(int j = 0;j<list.size();j++){
                        ps.setObject(j+1, list.get(j));
                    }
                    k++;
                }
                //更新
                ps.executeUpdate();
                if(ps != null) ps.close();
            }
            conn.commit();//提交事物
            return true;
        } catch (SQLException e) {
                try {
                    if(conn != null) conn.rollback();//回滚事物
                } catch (SQLException e1) {
                    System.out.println("事物回滚失败");
                }
                System.out.println("事物执行失败:"+e.getMessage());
        }finally{
            try{
                if(conn != null) conn.close();
            }catch(Exception e){
                
            }
        }
        return false;
    }
    
    /**
     * 执行事务
     * @param map sql集合
     * @return true-成功  false-失败
     */
    public static boolean executeTransaction(Map<String,Object[]> map){
        
        Connection conn = null;
        try {
            //链接
            conn = getConnection();
            conn.setAutoCommit(false);//不自动提交事务
            
            //遍历
            Iterator<String> it = map.keySet().iterator();
            while(it.hasNext()){
                String sql = it.next();
                PreparedStatement ps = conn.prepareStatement(sql);
                //判断是否有参数
                Object[] objs = map.get(sql);
                if(objs != null){
                    for(int i=0;i<objs.length;i++){
                        ps.setObject(i+1, objs[i]);
                    }
                }
                //更新
                ps.executeUpdate();
                //关闭
                if(ps != null) ps.close();
            }
            conn.commit();//提交
            return true;
            
        } catch (SQLException e) {
            System.out.println("执行事务失败:"+e.getMessage());
                try {
                    if(conn != null) conn.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
        } finally{
            
                try {
                    if(conn != null) conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
        return false;
        
    }

    /**
     * 关闭
     * 
     * @param conn
     *            链接对象
     * @param ps
     *            指令对象
     * @param rs
     *            结果解对象
     */
    public static void close(Connection conn, Statement ps, ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
            if (ps != null)
                ps.close();
            if (conn != null)
                conn.close(); //把链接对象放回到连接池中
        } catch (Exception e) {
            System.out.println("关闭资源失败");
        }
    }

}

例子2:

/**
 * 数据库操作类
 * 
 * @author Administrator
 * 
 */
public class DBUtilDBCP2 {
    
    private static DataSource ds;//数据源
    
    static {
        ds = getDataSource();
    }
    
    /**
     * 获取数据源
     * @return
     * @throws IOException 
     */
    private static DataSource getDataSource() {
        /*Properties p = new Properties();
        InputStream is = DBUtilDBCP2.class.getClassLoader().getResourceAsStream("dbcp.properties");
        try {
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String issss = p.getProperty("initialSize");
        System.out.println(issss);*/
        
        //创建资源对象                                                         只写文件名,不要后缀
        ResourceBundle rb = ResourceBundle.getBundle("dbcp");
        //创建数据源对象
        BasicDataSource ds = new BasicDataSource();
        //设置初始化连接数
        ds.setInitialSize(Integer.parseInt(rb.getString("initialSize")));
        //设置最大连接数
        ds.setMaxTotal(Integer.parseInt(rb.getString("maxTotal")));
        //设置最小空闲连接数
        ds.setMinIdle(Integer.parseInt(rb.getString("minIdle")));
        //设置最大空闲链接数  0-无限制
        ds.setMaxIdle(Integer.parseInt(rb.getString("maxIdle")));
        //设置最大等待毫秒数
        ds.setMaxWaitMillis(Long.parseLong(rb.getString("maxWaitMillis")));
        //设置账户
        ds.setUsername(rb.getString("username"));
        //设置密码
        ds.setPassword(rb.getString("password"));
        //设置链接路径
        ds.setUrl(rb.getString("url"));
        //设置驱动
        ds.setDriverClassName(rb.getString("driverClassName"));
        return ds;
    }
    
    
    
    /**
     * 获取链接
     * @return 一个新链接
     */
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = ds.getConnection(); //从数据源中获取一个链接
        } catch (Exception e) {
            System.out.println("获取链接失败:"+e);
        }
        return conn;
    }
    

    /**
     * 执行增删改草主
     * @param sql sql语句
     * @param paras 参数值
     * @return 受影响行数  -1表示异常
     */
    public static int executeUpdate(String sql, Object... paras) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 链接
            conn = getConnection();
            // 指令
            ps = conn.prepareStatement(sql);
            if (paras != null)
                for (int i = 0; i < paras.length; i++) {
                    ps.setObject(i + 1, paras[i]);
                }
            // 更新
            return ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(conn, ps, null);
        }
        return -1;
    }
    /**
     * 执行事务
     * @param sqls sql语句集合
     * @param paras sql语句中参数集合
     * @return true-成功  false-失败
     */
    public static boolean executeTransaction(List<String> sqls,List<List<Object>> paras){
        Connection conn = null;
        try {
            //链接
            conn = getConnection();
            conn.setAutoCommit(false); //不自动提交
            
            //遍历每条sql语句
            int k = 0; //防止某些sql语句没有参数
            for(int i = 0;i<sqls.size();i++){
                String sql = sqls.get(i);
                //指令
                PreparedStatement ps = conn.prepareStatement(sql);
                //执行的sql语句有参数
                if(sql.indexOf("?") != -1 ){
                    //为sql中参数参数赋值
                    List<Object> list = paras.get(k);
                    
                    for(int j = 0;j<list.size();j++){
                        ps.setObject(j+1, list.get(j));
                    }
                    k++;
                }
                //更新
                ps.executeUpdate();
                if(ps != null) ps.close();
            }
            conn.commit();//提交事物
            return true;
        } catch (SQLException e) {
                try {
                    if(conn != null) conn.rollback();//回滚事物
                } catch (SQLException e1) {
                    System.out.println("事物回滚失败");
                }
                System.out.println("事物执行失败:"+e.getMessage());
        }finally{
            try{
                if(conn != null) conn.close();
            }catch(Exception e){
                
            }
        }
        return false;
    }
    
    /**
     * 执行事务
     * @param map sql集合
     * @return true-成功  false-失败
     */
    public static boolean executeTransaction(Map<String,Object[]> map){
        
        Connection conn = null;
        try {
            //链接
            conn = getConnection();
            conn.setAutoCommit(false);//不自动提交事务
            
            //遍历
            Iterator<String> it = map.keySet().iterator();
            while(it.hasNext()){
                String sql = it.next();
                PreparedStatement ps = conn.prepareStatement(sql);
                //判断是否有参数
                Object[] objs = map.get(sql);
                if(objs != null){
                    for(int i=0;i<objs.length;i++){
                        ps.setObject(i+1, objs[i]);
                    }
                }
                //更新
                ps.executeUpdate();
                //关闭
                if(ps != null) ps.close();
            }
            conn.commit();//提交
            return true;
            
        } catch (SQLException e) {
            System.out.println("执行事务失败:"+e.getMessage());
                try {
                    if(conn != null) conn.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
        } finally{
            
                try {
                    if(conn != null) conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
        return false;
        
    }

    /**
     * 关闭
     * 
     * @param conn
     *            链接对象
     * @param ps
     *            指令对象
     * @param rs
     *            结果解对象
     */
    public static void close(Connection conn, Statement ps, ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
            if (ps != null)
                ps.close();
            if (conn != null)
                conn.close(); //把链接对象放回到连接池中
        } catch (Exception e) {
            System.out.println("关闭资源失败");
        }
    }

}

 

posted @ 2018-10-09 20:39  Aron_chen  阅读(311)  评论(0编辑  收藏  举报