zoukankan      html  css  js  c++  java
  • DBCP( 二) DataBase Connection Pool 的使用

    使用DBCP必须用的三个包:

    commons-dbcp-1.2.1.jar, commons-pool-1.2.jar, commons-collections-3.1.jar。

    配置参数。

    Java API: BasicDataSourceFactory.createDataSource(properties);

     

     

     

    package cn.itcast.jdbc;

    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Properties;

    import javax.sql.DataSource;

    import org.apache.commons.dbcp.BasicDataSourceFactory;

    import cn.itcast.jdbc.datasource.MyDataSource2;


    public final class JdbcUtils {
        private static String url = "jdbc:mysql://localhost:3306/jdbc";
        private static String user = "root";
        private static String password = "";
        private static DataSource myDataSource = null;

        private JdbcUtils() {
        }

        static {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                // myDataSource = new MyDataSource2();
                Properties prop = new Properties();
                // prop.setProperty("driverClassName", "com.mysql.jdbc.Driver");
                // prop.setProperty("user", "user");

                InputStream is = JdbcUtils.class.getClassLoader()
                        .getResourceAsStream("dbcpconfig.properties");
                prop.load(is);
                myDataSource = BasicDataSourceFactory.createDataSource(prop);//工厂模式,创建数据源
            } catch (Exception e) {
                throw new ExceptionInInitializerError(e);
            }
        }

        public static DataSource getDataSource() {
            return myDataSource;
        }

        public static Connection getConnection() throws SQLException {
            // return DriverManager.getConnection(url, user, password);
            return myDataSource.getConnection();
        }

        public static void free(ResultSet rs, Statement st, Connection conn) {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (st != null)
                        st.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    if (conn != null)
                        try {
                            conn.close();
                            // myDataSource.free(conn);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                }
            }
        }
    }

  • 相关阅读:
    使用 star UML制作的图
    评价片段
    项目部分
    用新学的知识 写了一段小代码
    常用系统存储过程
    考试小总结
    分页
    行转列面试题 事例
    子查询
    生成验证码的方法集合(一)
  • 原文地址:https://www.cnblogs.com/flying607/p/3464516.html
Copyright © 2011-2022 走看看