/** ####################################數據庫的連接池學習################################# * * * #####數據庫連接池 >1. 數據庫的連接對象創建工作,比較消耗性能。 >2.一開始現在內存中開辟一塊空間(集合) , 一開先往池子里面放置 多個連接對象。 后面需要連接的話,直接從池子里面去。不要去自己創建連接了。 使用完畢, 要記得歸還連接。確保連接對象能循環利用。 ###自定義數據庫連接池 * 代碼實現* 出現的問題:1. 需要額外記住 addBack方法2. 單例。3. 無法面向接口編程。 UserDao dao = new UserDaoImpl();dao.insert();DataSource dataSource = new MyDataSource();因為接口里面沒有定義addBack方法。 4. 怎么解決? 以addBack 為切入點。###解決自定義數據庫連接池出現的問題。 > 由于多了一個addBack 方法,所以使用這個連接池的地方,需要額外記住這個方法,并且還不能面向接口編程。> 我們打算修改接口中的那個close方法。 原來的Connection對象的close方法,是真的關閉連接。 > 打算修改這個close方法,以后在調用close, 并不是真的關閉,而是歸還連接對象。* * * ####開源連接池#### DBCP 1. 導入jar文件 2. 不使用配置文件* public void testDBCP01(){Connection conn = null;PreparedStatement ps = null;try {//1. 構建數據源對象BasicDataSource dataSource = new BasicDataSource();//連的是什么類型的數據庫, 訪問的是哪個數據庫 , 用戶名, 密碼。。//jdbc:mysql://localhost/bank 主協議:子協議 ://本地/數據庫dataSource.setDriverClassName("com.mysql.jdbc.Driver");dataSource.setUrl("jdbc:mysql://localhost/bank");dataSource.setUsername("root");dataSource.setPassword("root");//2. 得到連接對象conn = dataSource.getConnection();String sql = "insert into account values(null , ? , ?)";ps = conn.prepareStatement(sql);ps.setString(1, "admin");ps.setInt(2, 1000);ps.executeUpdate();} catch (SQLException e) {e.printStackTrace();}finally {JDBCUtil.release(conn, ps);}}* * * ####使用配置文件方式:Connection conn = null;PreparedStatement ps = null;try {BasicDataSourceFactory factory = new BasicDataSourceFactory();Properties properties = new Properties();InputStream is = new FileInputStream("src//dbcpconfig.properties");properties.load(is);DataSource dataSource = factory.createDataSource(properties);//2. 得到連接對象conn = dataSource.getConnection();String sql = "insert into account values(null , ? , ?)";ps = conn.prepareStatement(sql);ps.setString(1, "liangchaowei");ps.setInt(2, 100);ps.executeUpdate();} catch (Exception e) {e.printStackTrace();}finally {JDBCUtil.release(conn, ps);}* *###################配置文件模板##################################################*#連接設置 driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/bank username=root password=root#<!-- 初始化連接 --> initialSize=10#最大連接數量 maxActive=50#<!-- 最大空閑連接 --> maxIdle=20#<!-- 最小空閑連接 --> minIdle=5#<!-- 超時等待時間以毫秒為單位 6000毫秒/1000等于60秒 --> maxWait=60000#JDBC驅動建立連接時附帶的連接屬性屬性的格式必須為這樣:[屬性名=property;] #注意:"user" 與 "password" 兩個屬性會被明確地傳遞,因此這里不需要包含他們。 connectionProperties=useUnicode=true;characterEncoding=gbk#指定由連接池所創建的連接的自動提交(auto-commit)狀態。 defaultAutoCommit=true#driver default 指定由連接池所創建的連接的事務級別(TransactionIsolation)。 #可用值為下列之一:(詳情可見javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE defaultTransactionIsolation=READ_UNCOMMITTED########################################################################################* * ####################C3P0知識點##################################################################C3P0 > 拷貝jar文件 到 lib目錄###不使用配置文件方式Connection conn = null;PreparedStatement ps = null;try {//1. 創建datasourceComboPooledDataSource dataSource = new ComboPooledDataSource();//2. 設置連接數據的信息dataSource.setDriverClass("com.mysql.jdbc.Driver");//忘記了---> 去以前的代碼 ---> jdbc的文檔dataSource.setJdbcUrl("jdbc:mysql://localhost/bank");dataSource.setUser("root");dataSource.setPassword("root");//2. 得到連接對象conn = dataSource.getConnection();String sql = "insert into account values(null , ? , ?)";ps = conn.prepareStatement(sql);ps.setString(1, "admi234n");ps.setInt(2, 103200);ps.executeUpdate();} catch (Exception e) {e.printStackTrace();}finally {JDBCUtil.release(conn, ps);}######使用配置文件方式#####c3p0-config配置文件,xml文件。名字不可以改變<?xml version="1.0" encoding="UTF-8"?> <c3p0-config><!-- default-config 默認的配置, --><default-config><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost/bank</property><property name="user">root</property><property name="password">root</property><property name="initialPoolSize">10</property><property name="maxIdleTime">30</property><property name="maxPoolSize">100</property><property name="minPoolSize">10</property><property name="maxStatements">200</property></default-config><!-- This app is massive! --><named-config name="oracle"> <property name="acquireIncrement">50</property><property name="initialPoolSize">100</property><property name="minPoolSize">50</property><property name="maxPoolSize">1000</property><!-- intergalactoApp adopts a different approach to configuring statement caching --><property name="maxStatements">0</property> <property name="maxStatementsPerConnection">5</property><!-- he's important, but there's only one of him --><user-overrides user="master-of-the-universe"> <property name="acquireIncrement">1</property><property name="initialPoolSize">1</property><property name="minPoolSize">1</property><property name="maxPoolSize">5</property><property name="maxStatementsPerConnection">50</property></user-overrides></named-config></c3p0-config>#####代碼部分//默認會找 xml 中的 default-config 分支。 public class C3P0Demo02 {@Testpublic void testC3P0(){Connection conn = null;PreparedStatement ps = null;try {//就new了一個對象。在這種情況下c3p0會直接找到c3p0-config.xml文件//并且在c3p0-config.xml文件中默認的找到 default-config配置ComboPooledDataSource dataSource = new ComboPooledDataSource();//ComboPooledDataSource dataSource = new ComboPooledDataSource("oracle");//找到c3p0-config.xml文件中默認的找到named-config name="oracle"的配置//2. 得到連接對象conn = dataSource.getConnection();String sql = "insert into account values(null , ? , ?)";ps = conn.prepareStatement(sql);ps.setString(1, "wangwu2");ps.setInt(2, 2600);ps.executeUpdate();} catch (Exception e) {e.printStackTrace();}finally {JDBCUtil.release(conn, ps);}} }###########################################################################################* ###########DBUtils###增刪改 //dbutils 只是幫我們簡化了CRUD 的代碼, 但是連接的創建以及獲取工作。 不在他的考慮范圍QueryRunner主要是這個類QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());//增加 //queryRunner.update("insert into account values (null , ? , ? )", "aa" ,1000);//刪除 //queryRunner.update("delete from account where id = ?", 5);//更新 //queryRunner.update("update account set money = ? where id = ?", 10000000 , 6);* * * * * * ######查詢 1. 直接new接口的匿名實現類QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());Account account = queryRunner.query("select * from account where id = ?", new ResultSetHandler<Account>(){@Overridepublic Account handle(ResultSet rs) throws SQLException {Account account = new Account();while(rs.next()){String name = rs.getString("name");int money = rs.getInt("money");account.setName(name);account.setMoney(money);}return account;}}, 6);System.out.println(account.toString());2. 直接使用框架已經寫好的實現類。 * 查詢單個對象QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());//查詢單個對象Account account = queryRunner.query("select * from account where id = ?", new BeanHandler<Account>(Account.class), 8);* 查詢多個對象QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());List<Account> list = queryRunner.query("select * from account ",new BeanListHandler<Account>(Account.class));######ResultSetHandler 常用的實現類(重點) 以下兩個是使用頻率最高的BeanHandler, 查詢到的單個數據封裝成一個對象BeanListHandler, 查詢到的多個數據封裝 成一個List<對象>------------------------------------------ArrayHandler, 查詢到的單個數據封裝成一個數組ArrayListHandler, 查詢到的多個數據封裝成一個集合 ,集合里面的元素是數組。 MapHandler, 查詢到的單個數據封裝成一個mapMapListHandler,查詢到的多個數據封裝成一個集合 ,集合里面的元素是map。 ColumnListHandler KeyedHandler ScalarHandler##數據連接池* DBCP不使用配置使用配置* C3P0不使用配置使用配置 (必須掌握)* 自定義連接池 裝飾者模式##DBUtils> 簡化了我們的CRUD , 里面定義了通用的CRUD方法。 queryRunner.update();queryRunner.query* * * * * */
?