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,并以超链接形式标明文章原始出处,否则将 ...
随机推荐
- bestcoder r44 p3 hdu 5270 ZYB loves Xor II
这是昨晚队友跟我说的题,不知道当时是什么玄幻的事件发生了,,我看成了两两相乘的XOR 纠结了好长时间间 不知道该怎么办 今天早上看了下这道题,发现是两两相加的XOR 然后就想了想昨晚的思路 发现可做 ...
- discuz3.2x增加邮箱验证功能
为防止垃圾用户多次注册,为disczu增加邮箱验证功能. 大致分为二步: 1.申请邮箱,这里推荐使用腾讯免费企业邮箱:https://exmail.qq.com/portal/introducefre ...
- Selenium2Library+ride学习笔记
一.环境部署 1.安装python2.7编译环境.ride环境以及Selenium2Library环境,环境部署可参见前面几节. 2.启动RIDE编译环境,导入Selenium2Library库. ...
- nodejs javascript微信开发
1.当从第三方软件需要分享到微信的时候 需要给授权处理才能获得微信信息 比如 nickname 等昵称图像等 从第三方登陆跳转到微信分享页需要 shareurl = http://open.weixi ...
- zlog小试(C语言日志工具)
test.c #include <stdio.h> #include "zlog.h" int main(int argc, char** argv) { int rc ...
- build.prop修改详细说明
用RE进入/system/挂载读写,找到build.prop复制到/sdcarrd进行修改比较保险.也可以挂载读写后,直接选择用文本编辑器打开,进行编辑.乱改有风险,修改需谨慎.1.# begin b ...
- POST多个参数到Web API控制器
交互基于Json的方式打包传递就不介绍了,主要设置请求头为 contentType: "application/json", //必须有 数据位Json格式的字符串,在服务器端定义 ...
- windows7环境下 硬盘安装ubuntu 12.04 server版
之前一直用windows7环境下的虚拟机装的操作系统,但有时候在切换系统时老是死机,还是装一个硬盘版的ubuntu 12.04 server吧 先说一下本人的环境吧:windows 7 32位专业版+ ...
- [VBA]根据身份证号码计算年龄的Excel函数
是的,昨天刚发表了一篇和Excel自定义函数有关的博客,今天又一篇,有凑数的嫌疑.但是,保存知识和传播知识本来就是写博客的初衷,所以也并不多余. 如果不知道什么是Excel自定义函数,请移步这里[1] ...
- VS2013中C++创建DLL导出class类
1.创建"Win32 Console Application"项目,命名为"ClassDllLib",并在"Application type" ...