DataSource
数据库连接池原理:在内存中开辟一段存储空间用来存储多个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的更多相关文章
- Tomcat数据源(DataSource)简介
JDBC2.0提供了javax.sql.DataSource接口,它负责建立与数据库的连接,在应用程序中访问数据库时不必编写连接数据库的代码,可以直接从数据源获得数据库连接 1.数据库和连接池 在Da ...
- UITableview delegate dataSource调用探究
UITableview是大家常用的UIKit组件之一,使用中我们最常遇到的就是对delegate和dataSource这两个委托的使用.我们大多数人可能知道当reloadData这个方法被调用时,de ...
- transactionManager 以及datasource type解析
transactionManager 在 MyBatis 中有两种事务管理器类型(也就是 type=”[JDBC|MANAGED]”): JDBC – 这个配置直接简单使用了 JDBC 的提交和回滚设 ...
- MyBatis源码分析(5)——内置DataSource实现
@(MyBatis)[DataSource] MyBatis源码分析(5)--内置DataSource实现 MyBatis内置了两个DataSource的实现:UnpooledDataSource,该 ...
- 【验证】C# dataSource 的记忆功能
做项目时遇到的问题:dataSource被ComboBox引用过一次,会记忆最后一次选中的值,然后下一次再用时这个值会直接呈现在ComboBox中. 为验证是dataSource还是ComboBox自 ...
- Spring的三种通过XML实现DataSource注入方式
Spring的三种通过XML实现DataSource注入方式: 1.使用Spring自带的DriverManagerDataSource 2.使用DBCP连接池 3.使用Tomcat提供的JNDI
- Spring配置JNDI和通过JNDI获取DataSource
一.SpringJNDI数据源配置信息 <bean id="dataSource" class="org.springframework.jndi.JndiObje ...
- transactionManager的type与dataSource的type
1. 在ibatis的配置文件中dataSource 节点有这么个配置<datasource type="SIMPLE"></datasource>,根据原 ...
- dataGridViewX和数据库的链接之dataGridViewX1.DataSource = ds.Tables[0];
dataGridViewX1.DataSource = ds.Tables[0]; 1, dataGridViewX和数据库链接,如果我们用 dataGridViewX1.DataSource = d ...
- BW系统之间的InfoProvider数据传输:Export DataSource
声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...
随机推荐
- js引用类型姿势
栈 1)var a=new Array(),a.push(a,b,...),a.pop() queue 1)var a=new Array(), a.push(a,b,...),a.shift() a ...
- 织梦DEDECMS网站首页如何实现分页翻页
织梦DEDECMS模板网站首页如何实现首页分页和翻页 方法如下:(三种方法,自己选择一种来实现分页吧) 第一种:调用ajax和参数的(不推荐)1.必须在DEDE首页模板中的<head>&l ...
- Wireshark对ping报文的解码显示(BE与LE) 转自作者:易隐者
Wireshark对ping报文的解码显示(BE与LE) 我们非常熟悉ping报文的封装结构,但是,在这个报文解码里,我们发现wireshark的解码多了几个参数:Identifier(BE).Ide ...
- Guava 15新特性介绍
原文:http://www.javacodegeeks.com/2013/10/guava-15-new-features.html Guava 是众所周知的google出品的开源工具包,十分好用,本 ...
- JS模拟键盘事件 -- 原理及小例子
提问: 键盘默认事件,比如tab切换,alt+f4关闭,ctrl+t新建等,如果不想通过键盘而是一些按钮点击来触发这些功能,该咋办呢? 例子: 先以tab为例上一个小例子: <!DOCTYPE ...
- 一个基础的CURL类
/** * 一个基础的CURL类 * * @author Smala */ class curl{ public $ch; public $cookie = '/cookie'; public $rs ...
- 第一个微信小程序(实现点击一个按钮弹出toast)
今天根据网上的教程搭建了微信小程序的环境,然后看文档做了一个简单的小应用. 项目的目录是这个样子的: app.js.app.json.app.wxss是全局文件,必不可少的文件.定义在app.wxss ...
- 关于js事件冒泡和时间捕获
(1)冒泡型事件:事件按照从最特定的事件目标到最不特定的事件目标(document对象)的顺序触发. IE 5.5: div -> body -> document IE 6.0: div ...
- 带KEY的SCP命令,老是要查,这次写在这里吧,
有些东东记不住,急要用时老是想不起,放在这里吧, scp -r -i /xxx/rsa.key -P port user@ip:/source/ /target/
- JS打印、预览(IE,Chrome)
IE下: 调用IE内置打印组件完成web打印方案.IE调用ActiveX实现打印. 重点: 注意: 1.CSS对打印的控制: .Noprint{display:none;} .PageNext{pag ...