数据库连接池常用的有:dbcp,c3p0,druid
代码仓库(https://github.com/)
package com.huawei.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.alibaba.druid.pool.DruidDataSource;
public class DataSourceTest {
/**
*
* <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_user}" />
<property name="password" value="${jdbc_password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</bean>
*
*
*
*
*/
public static void main(String[] args) {
//创建了一个实例
DruidDataSource dataSource = new DruidDataSource();
//设置数据库连接地址
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
//设置用户名
dataSource.setUsername("root");
//设置密码
dataSource.setPassword("123456");
//设置初始化大小
dataSource.setInitialSize(1);
//设置在数据库连接词中的最小连接数
dataSource.setMinIdle(1);
//设置最大连接数
dataSource.setMaxActive(20);
//设置获取连接的最大等待时间
dataSource.setMaxWait(60000);
dataSource.setTimeBetweenEvictionRunsMillis(60000);
dataSource.setMinEvictableIdleTimeMillis(300000);
dataSource.setValidationQuery("SELECT 'X'");
dataSource.setTestOnBorrow(false);
dataSource.setTestOnReturn(false);
dataSource.setTestWhileIdle(true);
dataSource.setPoolPreparedStatements(false);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
try {
//得到连接
Connection connection = dataSource.getConnection();
PreparedStatement ps = connection.prepareStatement("select count(*) from users");
ResultSet rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getLong(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package com.huawei.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.alibaba.druid.pool.DruidDataSource;
/**
* @author Administrator
*
*/
public class DBUtil {
private DBUtil(){}
/**
* 得到数据库连接
* @return
*/
public static Connection getConnection(){
//显示加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
return connection;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static Connection getConn(){
try {
return Inner.dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private static class Inner{
public static DruidDataSource dataSource = null;
static{
//创建了一个实例
dataSource = new DruidDataSource();
//设置数据库连接地址
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
//设置用户名
dataSource.setUsername("root");
//设置密码
dataSource.setPassword("123456");
//设置初始化大小
dataSource.setInitialSize(1);
//设置在数据库连接池中的最小连接数
dataSource.setMinIdle(1);
//设置最大连接数
dataSource.setMaxActive(20);
//设置获取连接的最大等待时间
dataSource.setMaxWait(60000);
dataSource.setTimeBetweenEvictionRunsMillis(60000);
dataSource.setMinEvictableIdleTimeMillis(300000);
dataSource.setValidationQuery("SELECT 'X'");
dataSource.setTestOnBorrow(false);
dataSource.setTestOnReturn(false);
dataSource.setTestWhileIdle(true);
dataSource.setPoolPreparedStatements(false);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
}
}
/**
*
* 释放资源
* @param objects
*/
public static void close(Object ...objects){
if(objects!=null && objects.length>0){
try {
for(Object o:objects){
if(o instanceof ResultSet){
((ResultSet)o).close();
}else if(o instanceof Statement){
((Statement)o).close();
}else if(o instanceof Connection){
((Connection)o).close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//验证连接池是单例的
//System.out.println(Inner.dataSource == Inner.dataSource);
//System.out.println();
//System.out.println(Inner.dataSource);
}
}
package com.huawei.base;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.huawei.common.CallBack;
import com.huawei.common.Page;
import com.huawei.utils.BeanUtil;
import com.huawei.utils.DBUtil;
/**
* @author Administrator
*
*
* void executeQuery(String sql,Object[] parmas,CallBack callback) 通用的查询
* void executeUpdate(String sql,Object[] parmas) //通用的执行
*
* List<Object> findAll() //查询全部
* Object findOne(Integer id) //根据id查询一个
*
* void save(Object o) //给定一个对象 然后存储到数据库
*
* void update(Object o) //根据一个对象 更新数据库中所对应的字段
*
* void delete(Object o) //根据一个对象删除数据库中 对应的记录
* void deleteById(Integer id) //根据传入的id删除
* void delete(String sql,Object[] params) //自定义删除
*
*
*
*
*/
public abstract class BaseDAO<T,ID extends Serializable> {
//目标类 用于 反射
protected Class<T> clazz;
@SuppressWarnings("unchecked")
public BaseDAO() {
ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
//得到类上面的泛型参数的实际类型
clazz = (Class<T>) type.getActualTypeArguments()[0];
}
/**
* 通用的查寻方法
* @param sql 给定一个sql语句
* @param params 给定与sql语句中相对应的参数
* @param callBack 用于处理结果集的回调函数
*/
public void executeQuery(String sql,Object []params,CallBack callBack){
// Connection connection = DBUtil.getConnection();
Connection connection = DBUtil.getConn();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = connection.prepareStatement(sql);
//处理参数
if(params!=null && params.length>0){
for(int i=0;i<params.length;i++){
ps.setObject(i+1, params[i]);
}
}
System.out.println("ORM:"+sql);
rs = ps.executeQuery();
//处理业务逻辑
callBack.execute(rs);
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(rs,ps,connection);
}
}
/**
* 除了查询以外 的所有操作
* @param sql 给定一个sql语句
* @param params 参数
*/
public void executeUpdate(String sql,Object []params){
// Connection connection = DBUtil.getConnection();
Connection connection = DBUtil.getConn();
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(sql);
//处理参数
if(params!=null && params.length>0){
for(int i=0;i<params.length;i++){
ps.setObject(i+1, params[i]);
}
}
System.out.println("ORM:"+sql);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(ps,connection);
}
}
/**
* 通用查询
* @param sql
* @param params
* @return
*/
public List<T> find(String sql,Object []params){
final List<T> result = new ArrayList<T>();
this.executeQuery(sql, params, new CallBack() {
@Override
public void execute(ResultSet rs) throws SQLException {
//处理结果
try {
//得到虚拟表的 结构信息
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()){
//每一行代表一个对象
T o = clazz.newInstance();
//每一个单元格 代表对象中的一个属性
for(int i=0;i<rsmd.getColumnCount();i++){
//得到列明
String column_name = rsmd.getColumnName(i+1);
//根据列名去得到 clazz中的 属性
Field field = clazz.getDeclaredField(column_name);
//得到 set方法 setUsername(String name)
Method method = clazz.getDeclaredMethod(BeanUtil.setter(field), field.getType());
method.invoke(o, rs.getObject(column_name));
}
result.add(o);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
return result;
}
/**
* 查找全部
* @return 返回一个结果集
*/
public List<T> findAll(){
//存储结果集
String sql = "SELECT * FROM "+BeanUtil.getTableName(clazz);
return this.find(sql, null);
}
public T findById(ID id){
String sql = "SELECT * FROM "+BeanUtil.getTableName(clazz) +" WHERE id=?";
List<T> result = this.find(sql, new Object[]{id});
return result.size()>0?result.get(0):null;
}
public List<T> findBy(String prop,Object param){
String sql = "SELECT * FROM "+BeanUtil.getTableName(clazz) +" WHERE "+prop+"=?";
return this.find(sql, new Object[]{param});
}
public Page find4Page(Page page){
//构建sql语句
String sql = "SELECT * FROM "+BeanUtil.getTableName(clazz)+" LIMIT ?,?";
//得到数据
List<T> data = this.find(sql, new Object[]{(page.getCurr()-1)*page.getPageSize(),page.getPageSize()});
page.setRowCount(this.getCount());
page.setData(data);
return page;
}
public Long getCount(){
String sql = "SELECT COUNT(1) FROM "+BeanUtil.getTableName(clazz);
return this.getCount(sql, null);
}
public Long getCount(String sql,Object[] params){
final long []count = new long[]{0L};
this.executeQuery(sql, params, new CallBack() {
@Override
public void execute(ResultSet rs) throws SQLException {
while(rs.next()){
count[0] = rs.getLong(1);
}
}
});
return count[0];
}
/**
* 将给定的对象 持久化到数据库
* @param o 被持久化对象
*/
public void save(T o){
StringBuilder sb = new StringBuilder("INSERT INTO "+BeanUtil.getTableName(clazz)+" (");
StringBuilder values = new StringBuilder(" VALUES (");
//存储参数
List<Object> params = new ArrayList<Object>();
//得到所有的属性
Field []fields = clazz.getDeclaredFields();
try{
for(Field field:fields){
sb.append(BeanUtil.getColumnName(field)).append(",");
values.append("?,");
Method method = clazz.getDeclaredMethod(BeanUtil.getter(field));
//得到属性的值
params.add(method.invoke(o));
}
}catch (Exception e) {
e.printStackTrace();
}
//处理sql语句
sb.deleteCharAt(sb.length()-1).append(")");
values.deleteCharAt(values.length()-1).append(")");
sb.append(values);
this.executeUpdate(sb.toString(), params.toArray());
}
/**
* 更新 更新的对象中 一定要包含id
* @param o
*/
public void update(T o){
StringBuilder sb = new StringBuilder("UPDATE "+BeanUtil.getTableName(clazz)+" SET ");
//存储参数
List<Object> params = new ArrayList<Object>();
//得到所有的属性
Field []fields = clazz.getDeclaredFields();
Object id = null;
try{
for(Field field:fields){
//UPDATE USERS SET USERNAME=?,PASSWORD=?
String name = BeanUtil.getColumnName(field);
Method method = clazz.getDeclaredMethod(BeanUtil.getter(field));
//得到属性的值
Object value = method.invoke(o);
if("id".equals(name)){
id = value;
continue;
}
sb.append(name+"=?").append(",");
params.add(value);
}
}catch (Exception e) {
e.printStackTrace();
}
//处理sql语句
sb.deleteCharAt(sb.length()-1).append(" WHERE id=?");
if(id==null){
System.out.println("ID不能为空");
return;
}
params.add(id);
this.executeUpdate(sb.toString(), params.toArray());
}
@SuppressWarnings("unchecked")
public void delete(ID id){
//动态创建泛型数组
ID []ids = (ID[])Array.newInstance(id.getClass(), 1);
ids[0] =id;
this.delete(ids);
}
@SuppressWarnings("unchecked")
public void delete(T o){
try {
ID id = (ID)this.clazz.getDeclaredMethod("getId").invoke(o);
if(id!=null){
this.delete(id);
return ;
}
System.out.println("ID不能为空");
} catch (Exception e) {
e.printStackTrace();
}
}
public void delete(ID[] ids){
String sql = "DELETE FROM "+BeanUtil.getTableName(clazz) + " WHERE id in (?)";
this.executeUpdate(sql, ids);
}
public void delete(String sql,Object[] params){
this.executeUpdate(sql, params);
}
}
package com.huawei.test;
import java.util.List;
import java.util.Timer;
import com.huawei.dao.UsersDAO;
import com.huawei.po.Users;
public class UsersDAOTest {
public static void main(String[] args) {
UsersDAO dao = new UsersDAO();
/*for(int i=0;i<1000;i++){
Users users = new Users();
if(i%2==0){
users.setUsername("lisi"+i+i);
users.setPassword("lisipassword"+i+i);
users.setAge(20);
users.setEmail("lisi"+i+i+"@lisi.com");
}else{
users.setUsername("zhangsan"+i+i);
users.setPassword("zhangsanpassword"+i+i);
users.setAge(20);
users.setEmail("zhangsan"+i+i+"@zhangsan.com");
}
dao.save(users);
}*/
/*List<Users> users = dao.findAll();
for(Users user:users){
user.setAge((int)(Math.random()*99+1));
dao.update(user);
}*/
long start = System.currentTimeMillis();
for(int i=0;i<100;i++){
dao.findAll();
}
long end = System.currentTimeMillis();
System.out.println("耗时:"+(end-start)+" ms");
//System.out.println(dao.analyzeAge());
}
}