数据库连接池原理:在内存中开辟一段存储空间用来存储多个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. C/C++中虚函数的调用

    代码: #include <iostream> using namespace std; class A{ public: virtual void print(){ cout<&l ...

  2. Mysql 索引的基础(上)

    要理解Mysql 中索引是如何工作的,最简单的方法是去看一看书的"索引部分":如果想在一本书中找到某个特定的主题,一般先看书的"索引",找到对应的页码. 在My ...

  3. Sql Server批量停止作业

    CREATE Proc [dbo].[Proc_StopJob] as begin declare @I int declare @JobID uniqueidentifier -- 1. creat ...

  4. instanceof操作符判断对象类型

    instanceof 的语法格式如下: myobject instanceof ExampleClass myobject:某类的对象引用 ExampleClass:某个类 class Quadran ...

  5. iOS学习之自定义UItableViewCell

    在项目开发中,大部分情况下我们都需要自定义UITableViewCell, 今天就重点整理一下目前自己已经学过的自定义Cell的一些注意事项; 分步骤来写吧: 1.将自定义的Cell定义为属性; 2. ...

  6. laravel跟jquery之间传输json数据

    laravel代码: public function test(){ $arr = ["test1"=>"1","test2"=> ...

  7. repo init 时gpg: 无法检查签名:找不到公钥

    i found a solution here: http://www.marshut.com/wrrts/repo-release-1-12-4.html Sorry, I realized tod ...

  8. 用tee和script来记录终端输出

    如何在输出信息的同时把数据保存到文件当中? 一,如何把命令运行的结果保存到文件当中?这个问题太简单了,大家都知道,用 > 把输出转向就可以了 例子:[lhd@hongdi ~]$ ls > ...

  9. 【Xamarin 在Mac OS 上的部署安装环境】

    ******************没用Mac 的机子,也只能靠虚拟机了**********1 安装VMware 10 从网上下载即可2 下载MAC OS 10.9.5的安装镜像,网上有很多,最好使用 ...

  10. 【转】android 开发 命名规范

    原文网址:http://www.cnblogs.com/ycxyyzw/p/4103284.html 标识符命名法标识符命名法最要有四种: 1 驼峰(Camel)命名法:又称小驼峰命名法,除首单词外, ...