数据库连接池原理:在内存中开辟一段存储空间用来存储多个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. jQuery 2.2 和 1.12 新版本发布

    新年新气象,jQuery 团队于昨日发布了两个新版本:1.12 和 2.2.这两个版本都包含了大量的Bug修正和功能改进.基本上这会是3.0之前最后一次发布.不过由于3.0不做向下兼容,所以届时 jQ ...

  2. virtual pc中添加软盘支持

    最近对操作系统挺有兴趣的,实验了一下!准备找一个虚拟机,之前在xp上使用virtual pc感觉不错,准备在本机上装一下,但是发现居然不支持软盘了! 查阅了各种资料,终于找到了解决的办法. 1. 下载 ...

  3. C语言初学 计算二元一次方程的问题

    #include<stdio.h> #include<math.h> int main() { double a,b,c,disc,x1,x2; scanf("%lf ...

  4. Visual Studio下Qt编程中对中文的处理

    Visual Studio下Qt编程中对中文的处理 本文为原创文章,原文地址http://www.cnblogs.com/c4isr/p/qt_develop_in_vs.html Visual St ...

  5. LeetCode_Maximal Rectangle

    Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and ...

  6. tag_on_failure => [] # prevent default _grokparsefailure tag on real records

    [elk@zjtest7-frontend config]$ cat stdin04.conf input { stdin { } } filter { # drop sleep events gro ...

  7. 【转】Excel快捷键大全

    原文网址:http://www.bm8.com.cn/keyboard/excel.asp 显示和使用"Office 助手"注意 若要执行以下操作,"Microsoft ...

  8. 黑马程序员_Java面向对象_包

    7.包 7.1包(package) 对类文件进行分类管理. 给类提供多层命名空间. 写在程序文件的第一行. 类名的全称是:包名.类名. 包也是一种封装形式. 利用命令行自动生成文件夹格式:D:\jav ...

  9. 读书笔记:java并发

    java中主要的同步机制是关键字synchronized,它提供一种独占锁,但是 同步这个术语还包括validate类型的变量,显示锁(Explicit Lock)以及原子变量. -------显示锁 ...

  10. Java并发实现一(并发的实现之Thread和Runnable的区别)

    package com.subject01; public class ThreadOrRunnable { public static void main(String[] args) { Syst ...