1.使用c3p0数据源步骤):
a.下载c3p0jar,官网下载:https://sourceforge.net/projects/c3p0/;
b.导入jar包时,应该导入下面两个包;
c.编写c3p0配置文件,文件名必须为:c3p0-config.xml(还可以通过创建java类使用c3p0)
内容为,named-config 中name参数为配置名称(在使用连接池获取connection对象时需要);前四个为数据库连接的用户名,密码,驱动,url(一般改前四个就行);
<c3p0-config>
<!-- This app is massive! -->
<named-config name="mvcApp">
<property name="user">root</property>
<property name="password">123456</property>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3307/test?serverTimezone=UTC</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">10</property>
<property name="maxPoolSize">50</property>
<!-- intergalactoApp adopts a different approach to configuring statement caching -->
<property name="maxStatements">20</property>
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
2.编写jdbcUtills类:
import java.sql.SQLException;
import java.sql.Connection; import javax.activation.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class JDBCUtills { private static ComboPooledDataSource dataSource=null; //使用静态,对象只能实列化一次 static { dataSource=new ComboPooledDataSource("mvcApp");//("mvcApp")配置文件设置的名字 }
public static Connection getConnection(){//获得数据库连接 try { return dataSource.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static void closeConnection(Connection connection) {//关闭数据库连接 if(connection!=null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
注:
转载请注明来源,博客内容除表明内容为转载外均为原创,虽然是一个菜鸟写的博客,但也请尊重他人,尊重自己,谢谢。
以上为部分内容为个人见解,如有错误,还请斧正。