您的位置:首页 > 其它

c3p0的简单教程<个人学习笔记>

2015-12-28 20:40 447 查看
最近写课程设计。为了方便。于是使用到了c3p0,来分享下个人经验。

个人测试实在 linux 系统下进行的,一般其他系统也是一样。

这是我个人代码中体现的。仅仅是c3p0的一小部分功能。

<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///oa?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull</property>
<property name="user">root</property>
<property name="password">root</property>
</default-config>
</c3p0-config>


一般情况下,这样就可以了。

jdbc:mysql:///oa

为了防止乱码,一般加上

jdbc:mysql:///oa?useUnicode=true&characterEncoding=utf-8

我在处理date数值的适合(数据库),总是

error : Value ‘0000-00-00’ can not be represented as java.sql.Date

于是我就添加了这么一句话。 解决办法 :在 url后面添加 &zeroDateTimeBehavior=convertToNull

<property name="jdbcUrl">jdbc:mysql:///oa?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull</property>


也可以这样写,aaa标志

<named-config name="aaa">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///day12</property>
<property name="user">root</property>
<property name="password">root</property>
</named-config>


还可以在文件中添加对数据池的设置,如

<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>


经常使用的:

initialPoolSize:连接池初始化时创建的连接数,default : 3(建议使用)

minPoolSize:连接池保持的最小连接数,default : 3(建议使用)

maxPoolSize:连接池中拥有的最大连接数,如果获得新连接时会使连接总数超过这个值则不会再获取新连接,而是等待其他连接释放,所以这个值有可能会设计地很大,default : 15(建议使用)

acquireIncrement:连接池在无空闲连接可用时一次性创建的新数据库连接数,default : 3(建议使用)

*注意,以上文件配置实在c3p0-config.xml下进行的。*

ComboPooledDataSource source = new ComboPooledDataSource();
//          source.setDriverClass("com.mysql.jdbc.Driver");
//          source.setJdbcUrl("jdbc:mysql:///day11");
//          source.setUser("root");
//          source.setPassword("root");


当然。你也可以直接在代码中配置数据库的设置信息。

ComboPooledDataSource source = new ComboPooledDataSource();//这句代码很重要。连接数据池的。如果有标志则:

ComboPooledDataSource source = new ComboPooledDataSource(“aaa”);

下面给出一个简单的使用c3p0链接数据池的封装,

public class DaoUtils {
private static DataSource source = new ComboPooledDataSource();
private DaoUtils() {
}

public static DataSource getSource(){
return source;
}

public static Connection getConn(){
try {
return source.getConnection();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}


以及一个数据连接的线程池。(我没有使用过下面这段代码。)

public class PoolThread extends Thread {
@Override
public void run(){
ConnectionPool pool = ConnectionPool.getInstance();
Connection con = null;
PreparedStatement stmt= null;
ResultSet rs = null;
try{
con = pool.getConnection();
stmt = con.prepareStatement("select sysdate as nowtime from dual");
rs = stmt.executeQuery();
while(rs.next()){
System.out.println(Thread.currentThread().getId()+"---------------开始"+rs.getString("nowtime"));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}


我的课程设计使用了 DAO 和SERVER,工程模式实现的代码。下面是我的在DAO里面的代码实现。

一个最简单的查询列子:

select 返回一个类的对象

public Account findCustByIdreturnpass(String id) {
String sql = "select * from Account where id = ?";
try {
QueryRunner runner = new QueryRunner(DaoUtils.getSource());//DaoUtils.getSource()获取数据源池的source
//然后对数据进行操作,并且以类的形式返回数据。
return runner.query(sql, new BeanHandler<Account>(Account.class), id);
} catch (Exception e) {
throw new RuntimeException();
}


简单的更新:

public int updataPasswordbyId(String id, String password) {
String sql = "update Account set password = ? where id = ?";
try {
QueryRunner runner = new QueryRunner(DaoUtils.getSource());
int count = runner.update(sql, password, id);
if (count <= 0) {
System.out.println("数据库update失败,AccountDao");
return 0;
}
return 1;
} catch (Exception e) {
}

}


以类的数值进行返回数据。

runner.query(sql, new BeanListHandler<apply>(apply.class),newId);


也可以这样搭配来使用:

ComboPooledDataSource source = new ComboPooledDataSource();
conn = source.getConnection();
ps = conn.prepareStatement("select * from Account");
rs = ps.executeQuery();
while(rs.next()){
String name = rs.getString("name");
System.out.println(name);
}


第二中配置方法:

c3p0.properties文件中:

c3p0.driverClass=com.mysql.jdbc.Driver

c3p0.jdbcUrl=jdbc:mysql://localhost:3306/oa

c3p0.user=root

c3p0.password=root

——————————-

连接池初始化时创建的连接数

c3p0.initialPoolSize=3

连接池保持的最小连接数

c3p0.minPoolSize=3

连接池在无空闲连接可用时一次性创建的新数据库连接数,default:3

c3p0.acquireIncrement=3

连接池中拥有的最大连接数,如果获得新连接时会使连接总数超过这个值则不会再获取新连接,而是等待其他连接释放,所以这个值有可能会设计地很大,default : 15

c3p0.maxPoolSize=15

连接的最大空闲时间,如果超过这个时间,某个数据库连接还没有被使用,则会断开掉这个连接,单位秒

c3p0.maxIdleTime=100

连接池在获得新连接失败时重试的次数,如果小于等于0则无限重试直至连接获得成功

c3p0.acquireRetryAttempts=30

连接池在获得新连接时的间隔时间

c3p0.acquireRetryDelay=1000

顺便说一下

jdbc使用方法;

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
//这是自己定义的类,
MyPool pool = new MyPool();
try{
//仅仅返回的是conn,相当于这样。
//Connection conn = DriverManager.getConnection("jdbc:mysql:///day11","root","root");
conn = pool.getConnection();
ps = conn.prepareStatement("select * from account");
rs = ps.executeQuery();
while(rs.next()){
String name = rs.getString("name");
System.out.println(name);
}


dbcp的使用方法

1,在java代码中实现数据的配置信息。

BasicDataSource source = new BasicDataSource();
//      source.setDriverClassName("com.mysql.jdbc.Driver");
//      source.setUrl("jdbc:mysql:///oa");
//      source.setUsername("root");
//      source.setPassword("root");


或者在dpcp.properties配置信息文件。

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day11
username=root
password=root


然后在(不管是在配置文件里面写,还是在java代码里面写)

try {
Properties prop = new Properties();
prop.load(new FileReader("dbcp.properties"));
BasicDataSourceFactory factory = new BasicDataSourceFactory();
DataSource source = factory.createDataSource(prop);

conn = source.getConnection();
ps = conn.prepareStatement("select * from account");
rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
System.out.println(name);
}


c3p0乱码,在url后面添加?useUnicode=true&characterEncoding=utf-8

在mysql下设置utf8的编码格式,show variables like ‘character%’;

创建完数据库后,添加utf8的设置

alter database 库 default character set utf8;

alter table 表 default cahracter set utf8;

开启:sudo /etc/init.d/mysql start
停止:sudo /etc/init.d/mysql stop
重启:sudo /etc/init.d/mysql restart
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: