本文主要介绍了在Tomcatc3p0中配置jnid数据源的两种实现方法的分析。通过示例代码非常详细的介绍,对大家的学习或者工作都有一定的参考价值,有需要的朋友可以参考一下。
使用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="DBConnection" 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&serverTimezone=GMT%2B8"/>获取连接
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ try{ //创建上下文 Contextcontext=newInitialContext(); //获取数据源 ComboPooledDataSourcecomboPooledDataSource=(ComboPooledDataSource)context.lookup ("java:comp/env/jdbc/myDB"); //获取数据库连接 Connectionconnection=comboPooledDataSource.getConnection(); if(!connection.isClosed()){ System.out.println("已经连接成功"); } }catch(NamingExceptione){ e.printStackTrace(); }catch(SQLExceptione){ e.printStackTrace(); } }使用德鲁伊
导入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&serverTimezone=GMT%2B8" username="root" password="123456" maxActive="50" maxWait="10000" removeabandoned="true" removeabandonedtimeout="60" logabandoned="false" filters="stat"/>获取连接
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ try{ //获取上下文对象 Contextcontext=newInitialContext(); //获取数据源 DataSourceds=(DataSource)context.lookup("java:comp/env/jdbc/MysqlDataSource"); //获取Connection对象 Connectionconnection=ds.getConnection(); if(!connection.isClosed()){ System.out.println("连接成功"); } }catch(NamingExceptione){ e.printStackTrace(); }catch(SQLExceptione){ e.printStackTrace(); } }这就是本文的全部内容。希望对大家的学习有帮助,支持我们。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)