Java dbcp連接池基本使用方法詳解
1、依賴api的使用
導(dǎo)入jar包
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.7.0</version> </dependency>
導(dǎo)入dbcp.properties配置文件
獲取連接
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Properties properties=new Properties(); //獲取dbcp配置文件對(duì)應(yīng)輸入流 InputStream inputStream=DbcpServlet.class.getClassLoader().getResourceAsStream('dbcp.properties'); //加載dbcp配置文件 properties.load(inputStream); BasicDataSource basicDataSource=null; try { //數(shù)據(jù)源對(duì)象 basicDataSource=BasicDataSourceFactory.createDataSource(properties); //獲取數(shù)據(jù)庫連接 Connection connection=basicDataSource.getConnection(); System.out.println(connection); } catch (Exception e) { e.printStackTrace(); } }
2、依賴tomcat容器的使用
利用jndi機(jī)制實(shí)現(xiàn),jndi(命名及目錄查找接口),將數(shù)據(jù)源連接池的配置信息在容器(Tomcat)實(shí)現(xiàn)配置
具體如何實(shí)現(xiàn)配置
在tomcat的context.xml文件加入數(shù)據(jù)源配置
<Resource <!--數(shù)據(jù)源名字--> name='jdbc/news' <!--驗(yàn)證數(shù)據(jù)源的容器類型--> auth='Container' type='javax.sql.DataSource' <!--最大連接數(shù)據(jù)庫連接對(duì)象的數(shù)量100--> maxActive='100' <!--最大空閑數(shù)是30--> maxIdle='30' <!--最大等待時(shí)間--> maxWait='10000' <!--數(shù)據(jù)庫用戶名--> username='root' <!--數(shù)據(jù)庫密碼--> password='123456' <!--數(shù)據(jù)庫驅(qū)動(dòng)--> driverClassName='com.mysql.cj.jdbc.Driver' <!--數(shù)據(jù)庫url--> url='jdbc:mysql://localhost:3306/yl?characterEncoding=utf8&serverTimezone=GMT%2B8'/>
獲取連接
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //獲取上下文對(duì)象 Context ctx = new InitialContext(); //通過jndi命名服務(wù),找到數(shù)據(jù)源配置 DataSource ds = (DataSource) ctx.lookup('java:comp/env/jdbc/news'); //獲取數(shù)據(jù)庫連接 Connection connection = ds.getConnection(); if (!connection.isClosed()) {System.out.println('連接成功'); } } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IntelliJ IDEA刪除類的方法步驟2. IntelliJ IDEA創(chuàng)建web項(xiàng)目的方法3. docker /var/lib/docker/aufs/mnt 目錄清理方法4. 詳解PHP laravel中的加密與解密函數(shù)5. IntelliJ IDEA導(dǎo)出項(xiàng)目的方法6. idea自定義快捷鍵的方法步驟7. IntelliJ IDEA配置Tomcat服務(wù)器的方法8. Intellij IDEA 關(guān)閉和開啟自動(dòng)更新的提示?9. 刪除docker里建立容器的操作方法10. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法

網(wǎng)公網(wǎng)安備