当前位置:   首页安装配置Tomcatc3p0配置jnid数据源2种实现方法解析

Tomcatc3p0配置jnid数据源2种实现方法解析

发布日期:2021-05-24 15:55 | 文章来源:CSDN

使用c3p0

导入c3p0jar包

<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
  <dependency>
   <groupId>com.mchange</groupId>
   <artifactId>c3p0</artifactId>
   <version>0.9.5.2</version>
  </dependency>

在tomcat的context.xml文件加入数据源配置

<Resource 
    auth="Container" 
    description="DB Connection" 
    driverClass="com.mysql.jdbc.Driver" 
    maxPoolSize="100" minPoolSize="2" 
    acquireIncrement="2" 
    name="jdbc/myDB" 
    user="root" 
    password="123456" 
    factory="org.apache.naming.factory.BeanFactory" 
    type="com.mchange.v2.c3p0.ComboPooledDataSource" 
    jdbcUrl="jdbc:mysql://localhost:3306/attendance_system?characterEncoding=utf8&amp;serverTimezone=GMT%2B8" />

获取连接

protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      //创建上下文
      Context context=new InitialContext();
      //获取数据源
      ComboPooledDataSource comboPooledDataSource= (ComboPooledDataSource) context.lookup
          ("java:comp/env/jdbc/myDB");
      //获取数据库连接
      Connection connection=comboPooledDataSource.getConnection();
      
      if(!connection.isClosed()){
        System.out.println("已经连接成功");
      }
    } catch (NamingException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

使用druid

导入jar包

 <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
  <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.1.16</version>
  </dependency>

在tomcat的context.xml文件加入数据源配置

<Resource
  name="jdbc/MysqlDataSource"
  factory="com.alibaba.druid.pool.DruidDataSourceFactory"
  auth="Container"
  type="javax.sql.DataSource"
  driverClassName="com.mysql.cj.jdbc.Driver"
  url="jdbc:mysql://localhost:3306/yl?characterEncoding=utf8&amp;serverTimezone=GMT%2B8"
  username="root"
  password="123456"
  maxActive="50"
  maxWait="10000"
  removeabandoned="true"
  removeabandonedtimeout="60"
  logabandoned="false"
  filters="stat"/>

获取连接

protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      //获取上下文对象
      Context context=new InitialContext();
      //获取数据源
      DataSource ds= (DataSource) context.lookup("java:comp/env/jdbc/MysqlDataSource");
      //获取Connection对象
      Connection connection=ds.getConnection();
​
      if(!connection.isClosed()){
        System.out.println("连接成功");
​
      }
    } catch (NamingException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

联系我们
关于使用场景和技术架构的更多咨询,请联系我们的销售和技术支持团队。
Yingsoo Host

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部