数据库连接池原理:在内存中开辟一段存储空间用来存储多个Connection连接,避免频繁的创建Connection,从而提高效率。代码如下:

package jcbc.ds.test1;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import JDBCUtil.JDBCUtil; import org.junit.Test; public class JDBCDS1 {
//List 保存connection
private static List<Connection> list = new ArrayList<Connection>();
//获取创建连接
static{
try {
for (int i = 0 ;i < 10; i++){
Connection conn =JDBCUtil.getConnection();//再JDBCUtil类中创建了获取连接的方法
//存入list中
list.add(conn);
} } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
//从连接池中拿出连接(拿出一个连接池就少一个)
@Test
public Connection getConnection(){
return list.remove(0);
}
//添加到连接池
public void releaseConnection(Connection conn){
list.add(conn);
}
}

DataSource接口:

package jcbc.ds.test1;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger; import javax.sql.DataSource; import org.junit.Test; import JDBCUtil.JDBCUtil; public class JDBCDS2 implements DataSource { //实现DataSource 接口 private static List<Connection> list = new ArrayList<Connection>(); static{
try {
for (int i = 0 ;i < 10; i++){
Connection conn =JDBCUtil.getConnection();
list.add(conn);
} } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public Connection getConnection() throws SQLException {
// TODO Auto-generated method stub
Connection conn = list.remove(0);
if(conn != null){
return conn;
}
else {
throw new RuntimeException("服务器真忙。。。。");
}
}
public Connection getConnection(String username, String password) throws SQLException { return null; } @Override
public PrintWriter getLogWriter() throws SQLException {
return null;
} @Override
public void setLogWriter(PrintWriter out) throws SQLException { } @Override
public void setLoginTimeout(int seconds) throws SQLException { } @Override
public int getLoginTimeout() throws SQLException {
return 0;
} @Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
} @Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
} }

DBCP:

  

package jcbc.ds.test1;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties; import javax.sql.DataSource; import org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory; public class DBCP1 {
//使用DBCP的步骤:
// 1.拷jar包:commons-dbcp-1.4.jar,commons-pool-1.5.6.jar
// 2.将properties文件拷到src目录下
// 3.改配置文件
private static DataSource datasource = null;
static{
//加载配置文件
InputStream is =DBCP1.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties pro = new Properties();
try {
pro.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try { //获取datasource
datasource = BasicDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
public static Connection getConnection() throws SQLException{
//通过datasource获取Connection
return datasource.getConnection();
}
public static DataSource getDataSource(){
//返回datasource
return datasource;
} }

testDBCP:

package jcbc.ds.test1;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import org.junit.Test; import JDBCUtil.JDBCUtil;
import jcbc.ds.test1.*;
public class TestDBCP {
@Test
public void test() throws SQLException{
Connection conn = DBCP1.getConnection();
Statement statement = conn.createStatement(); ResultSet resultset = statement.executeQuery("select * from customers");
while(resultset.next()){
System.out.println(resultset.getString("id"));
}
conn.close(); } }
aa
1

C3P0的使用:

      1.先把c3p0-0.9.5.2.jar和mchange-commons-java-0.2.11.jar两个jar包拷贝到lib目录下

      2.新建类:代码如下(获取Connection类和测试c3p0类)

      

 package jcbc.ds.test1;

 import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0 {
//通过ComboPooledDataSource获取datasource对象
private static ComboPooledDataSource datasource = new ComboPooledDataSource() ;
static{
try {
//在static代码块中获得与数据库的连接
datasource.setDriverClass("com.mysql.jdbc.Driver");
datasource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb1");
datasource.setUser("root");
datasource.setPassword("123456");
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
//返回数据库连接
return datasource.getConnection();
}
public static DataSource getDataSource(){
//返回datasource
return datasource;
} }

c3p0

 package jcbc.ds.test1;

 import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import jcbc.ds.test1.*; import org.junit.Test; public class TestC3p0 {
@Test
public void TestC3p0() throws SQLException{
Connection conn = C3P0.getConnection();
Statement statement = conn.createStatement(); ResultSet resultset = statement.executeQuery("select * from customers");
while(resultset.next()){
System.out.println(resultset.getDate("date"));
}
conn.close();
} }

testC3p0

 九月 09, 2016 8:57:25 下午 com.mchange.v2.log.MLog <clinit>
信息: MLog clients using java 1.4+ standard logging.
九月 09, 2016 8:57:25 下午 com.mchange.v2.c3p0.C3P0Registry banner
信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
九月 09, 2016 8:57:25 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge38g9j462l0p1hqpxz7|311d617d, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge38g9j462l0p1hqpxz7|311d617d, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/mydb1, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
Fri Sep 09 20:57:26 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Sep 09 20:57:26 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Sep 09 20:57:26 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
1990-09-09
1994-02-09

result

C3p0通过配置文件使用:

写好配置文件后的代码编写

 package jcbc.ds.test1;

 import java.sql.Connection;
import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P02 {
private static ComboPooledDataSource datasource = new ComboPooledDataSource();
public static Connection getConnection() throws SQLException{
//通过datasource获取Connection
return datasource.getConnection();
}
public static DataSource getDataSource(){
//返回datasource
return datasource;
} }

c3p0_config

package jcbc.ds.test1;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import org.junit.Test; public class TestC3p02 {
@Test
public void test() throws SQLException{
Connection conn = C3P02.getConnection();
Statement statement = conn.createStatement(); ResultSet resultset = statement.executeQuery("select * from customers");
while(resultset.next()){
System.out.println(resultset.getString("id"));
}
conn.close(); } }

testconfigc3p0

 九月 09, 2016 9:17:40 下午 com.mchange.v2.log.MLog <clinit>
信息: MLog clients using java 1.4+ standard logging.
九月 09, 2016 9:17:40 下午 com.mchange.v2.c3p0.C3P0Registry banner
信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
九月 09, 2016 9:17:40 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge38g9j46smme1tkotcn|2f333739, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge38g9j46smme1tkotcn|2f333739, idleConnectionTestPeriod -> 0, initialPoolSize -> 10, jdbcUrl -> jdbc:mysql://localhost:3306/mydb1, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 30, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 100, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 10, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
Fri Sep 09 21:17:41 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Sep 09 21:17:41 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Sep 09 21:17:41 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Sep 09 21:17:41 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri Sep 09 21:17:41 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
aa
1

result

DataSource的更多相关文章

  1. Tomcat数据源(DataSource)简介

    JDBC2.0提供了javax.sql.DataSource接口,它负责建立与数据库的连接,在应用程序中访问数据库时不必编写连接数据库的代码,可以直接从数据源获得数据库连接 1.数据库和连接池 在Da ...

  2. UITableview delegate dataSource调用探究

    UITableview是大家常用的UIKit组件之一,使用中我们最常遇到的就是对delegate和dataSource这两个委托的使用.我们大多数人可能知道当reloadData这个方法被调用时,de ...

  3. transactionManager 以及datasource type解析

    transactionManager 在 MyBatis 中有两种事务管理器类型(也就是 type=”[JDBC|MANAGED]”): JDBC – 这个配置直接简单使用了 JDBC 的提交和回滚设 ...

  4. MyBatis源码分析(5)——内置DataSource实现

    @(MyBatis)[DataSource] MyBatis源码分析(5)--内置DataSource实现 MyBatis内置了两个DataSource的实现:UnpooledDataSource,该 ...

  5. 【验证】C# dataSource 的记忆功能

    做项目时遇到的问题:dataSource被ComboBox引用过一次,会记忆最后一次选中的值,然后下一次再用时这个值会直接呈现在ComboBox中. 为验证是dataSource还是ComboBox自 ...

  6. Spring的三种通过XML实现DataSource注入方式

    Spring的三种通过XML实现DataSource注入方式: 1.使用Spring自带的DriverManagerDataSource 2.使用DBCP连接池 3.使用Tomcat提供的JNDI

  7. Spring配置JNDI和通过JNDI获取DataSource

    一.SpringJNDI数据源配置信息 <bean id="dataSource" class="org.springframework.jndi.JndiObje ...

  8. transactionManager的type与dataSource的type

    1. 在ibatis的配置文件中dataSource 节点有这么个配置<datasource type="SIMPLE"></datasource>,根据原 ...

  9. dataGridViewX和数据库的链接之dataGridViewX1.DataSource = ds.Tables[0];

    dataGridViewX1.DataSource = ds.Tables[0]; 1, dataGridViewX和数据库链接,如果我们用 dataGridViewX1.DataSource = d ...

  10. BW系统之间的InfoProvider数据传输:Export DataSource

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

随机推荐

  1. 自定义标签(JSTL)

    自定义标签的步骤: 1.确定需求,如:用<my:date/>输出当前时间 2.编写Java类:需要实现实现接口javax.servlet.jsp.tagext.JspTag 具体的接口为: ...

  2. window对象BOM

    BOM的和新对象是window,他表示流浪器的一个实例,作为一个Global对象,有权访问parseInt()等方法 在全局作用域声明的变量,函数都有钱访问 ; function sayName () ...

  3. HTML5画布(变形)

    坐标变换 案例1: <!DOCTYPE html><html><head lang="en"> <meta charset="U ...

  4. QQ在线客服

    css代码: .float0831 { POSITION: fixed; TOP: 180px; RIGHT: 1px; _position: absolute } .float0831 A { CO ...

  5. SPI协议总结

    四种工作模式: Mode 0 CPOL=0, CPHA=0 Mode 1 CPOL=0, CPHA=1Mode 2 CPOL=1, CPHA=0 Mode 3 CPOL=1, CPHA=1 常使用Mo ...

  6. BZOJ1672: [Usaco2005 Dec]Cleaning Shifts 清理牛棚

    1672: [Usaco2005 Dec]Cleaning Shifts 清理牛棚 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 414  Solved: ...

  7. 【POJ2242】The Circumference of the Circle(初等几何)

    已知三点坐标,算圆面积. 使用初等几何知识,根据海伦公式s = sqrt(p(p - a)(p - b)(p - c)) 和 外接圆直径 d = a * b * c / (2s) 来直接计算. #in ...

  8. Java Spring各种依赖注入注解的区别

    Spring对于Bean的依赖注入,支持多种注解方式: @Resource javax.annotation JSR250 (Common Annotations for Java) @Inject ...

  9. JAVA判断上传表单中file是否为空

    <form action="update.do"method="post" enctype="multipart/form-data" ...

  10. iOS7状态栏字体颜色修改

    iOS7中,默认的状态栏字体颜色是黑色的,如何修改为其它颜色呢? 1.在项目的*info.plist中增加 View controller-based status bar appearance 属性 ...