package com.dl.network_flow.db;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.log4j.Logger; /*oracle和mysql的分页区别:
* 1、语句的记录起始部分不一样,oralce是“记录查询结果的结束行”和“查询结果的开始行”,mysql是从“记录起始行”和“该页显示的条数”
* 2、数据基数:oracle是从1开始,mysql是从0开始
* */
public class BaseDao { protected Logger log = Logger.getLogger(this.getClass()); /**
* 执行新增和修改的数据库操作,不用处理返回的ResultSet结果集
*
* @param sql
* sql语句
* @param params
* 参数,若为日期,需要特别处理
* @return
*/
public int executeSql(String sql, Object[] params) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null; try {
connection = ConnectionFactory.getInstance().getConnection();
preparedStatement = connection.prepareStatement(sql);
// log.debug("executeSql sql = " + sql);
// log.debug("params = " + params);
if (params != null) {
// 设置sql语句参数
for (int i = 0; i < params.length; i++) {
// log.debug("params[i] = " + params[i]);
if (params[i] != null) {
if (params[i] instanceof java.util.Date) {
preparedStatement
.setTimestamp(i + 1, new Timestamp(
((Date) params[i]).getTime()));
} else {
preparedStatement.setObject(i + 1, params[i]);
}
} else {
preparedStatement.setString(i + 1, "");
}
}
}
return preparedStatement.executeUpdate();
} catch (SQLException e) {
log.error(e.getMessage() + "code = " + e.getErrorCode()+",sql:"+sql);
// /throw new RuntimeException(e.getMessage() + "code = " +
// e.getErrorCode());
return -1;
} finally {
ConnectionFactory.getInstance().closeConnection(connection,
preparedStatement, resultSet);
} } /*
* 批量执行sql语句 paramsArr是个2维数组,第一维度表示各条记录,第二维度表示各条记录里的各个parameter值
*/
public int[] executeBatchSql(String sql, Object[][] paramsArr) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = ConnectionFactory.getInstance().getConnection();
preparedStatement = connection.prepareStatement(sql); if (paramsArr != null) {
for (int s = 0; s < paramsArr.length; s++) {
Object[] params = paramsArr[s];
if (params != null) {
// 设置sql语句参数
for (int i = 0; i < params.length; i++) {
if (params[i] != null) {
if (params[i] instanceof java.util.Date) {
preparedStatement.setTimestamp(
i + 1,
new Timestamp(((Date) params[i])
.getTime()));
} else {
preparedStatement.setObject(i + 1,
params[i]);
}
} else {
preparedStatement.setString(i + 1, "");
}
}
preparedStatement.addBatch();// /批量增加1条
}
}
}
return preparedStatement.executeBatch();// /批量执行
} catch (SQLException e) {
e.printStackTrace();
// log.error(e.getMessage() + "code = " + e.getErrorCode());
log.error(e.getMessage() + "code = " + e.getErrorCode()+",sql:"+sql);
} finally {
ConnectionFactory.getInstance().closeConnection(connection,preparedStatement, resultSet);
}
return null;
} /**
* 批量执行不同的sql语句 不包含查询
* executeBatchSql
* @time 2015年9月23日下午4:23:16
* @packageName com.dl.ios6
* @param sql 多个sql语句的数组
* @return
*/
public int[] executeBatchSql(String[] sql){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null; connection = ConnectionFactory.getInstance().getConnection();
Statement state = null;
try {
if(sql!=null&&sql.length>0){
boolean autoCommit = connection.getAutoCommit();
connection.setAutoCommit(false);
state = connection.createStatement();
for (int i = 0; i < sql.length; i++) {
state.addBatch(sql[i]);
}
int j[] = state.executeBatch();
connection.commit();
connection.setAutoCommit(autoCommit);
state.close();
ConnectionFactory.getInstance().closeConnection(connection, preparedStatement, resultSet);
return j;
}
} catch (SQLException e) {
state = null;
ConnectionFactory.getInstance().closeConnection(connection, preparedStatement, resultSet);
}
return null;
} /*
* 批量执行sql语句 paramsArr是个2维数组,第一维度表示各条记录,第二维度表示各条记录里的各个parameter值
*/
public int[] executeBatchSql(String sql, List<Object[]> paramsList) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try { connection = ConnectionFactory.getInstance().getConnection();
preparedStatement = connection.prepareStatement(sql); if (paramsList == null){
return null;
}
// /遍历所有记录
for (int i = 0; i < paramsList.size(); i++) {
Object[] tObj = paramsList.get(i);
if (tObj == null) {
continue;
}
// /遍历记录中的每个字段
for (int j = 0; j < tObj.length; j++) {
Object curObj = tObj[j];
if (curObj != null) {
if (curObj instanceof java.util.Date) {
preparedStatement.setTimestamp(j + 1,
new Timestamp(((java.util.Date) curObj).getTime()));
} else {
preparedStatement.setObject(j + 1, curObj);
}
} else{
preparedStatement.setString(j + 1, "");
}
}// /遍历记录中的每个字段
preparedStatement.addBatch();// /添加一条记录
}// /遍历所有记录 return preparedStatement.executeBatch();// /批量执行
} catch (SQLException e) {
e.printStackTrace();
log.error(e.getMessage() + "code = " + e.getErrorCode()+",sql:"+sql);
} finally {
ConnectionFactory.getInstance().closeConnection(connection,
preparedStatement, resultSet);
}
return null;
} /*
* 执行sql操作,把sql和params结合成一个sql语句
* 执行sql查询的结果集交给sqlExecute这个接口函数处理,处理后封装的对象放到List里
*/
public List<Map<String, Object>> queryForList(String sql, Object[] params) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null; try {
connection = ConnectionFactory.getInstance().getConnection();
preparedStatement = connection.prepareStatement(sql);
// 设置sql语句参数
if (params != null) {
for (int i = 0; i < params.length; i++) {
// log.debug("params[i] = " + params[i]);
preparedStatement.setObject(i + 1, params[i]);
}
}
resultSet = preparedStatement.executeQuery();
ResultSetMetaData md = resultSet.getMetaData(); // 得到结果集(rs)的结构信息,比如字段数、字段名等
int columnCount = md.getColumnCount();
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> rowData = new HashMap<String, Object>();
while (resultSet.next()) {
rowData = new HashMap<String, Object>(columnCount);
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnLabel(i), resultSet.getObject(i));
}
list.add(rowData);
} return list;
} catch (SQLException e) {
// log.error(e.getMessage());
log.error(e.getMessage() + "code = " + e.getErrorCode()+",sql:"+sql);
} finally {
ConnectionFactory.getInstance().closeConnection(connection,
preparedStatement, resultSet);
}
return null;
} public Map<String, Object> queryForMap(String sql, Object[] params) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null; try {
connection = ConnectionFactory.getInstance().getConnection();
preparedStatement = connection.prepareStatement(sql);
// 设置sql语句参数
if (params != null) {
for (int i = 0; i < params.length; i++) {
// log.debug("params[i] = " + params[i]);
preparedStatement.setObject(i + 1, params[i]);
}
}
resultSet = preparedStatement.executeQuery();
ResultSetMetaData md = resultSet.getMetaData(); // 得到结果集(rs)的结构信息,比如字段数、字段名等
int columnCount = md.getColumnCount();
Map<String, Object> rowData = new HashMap<String, Object>();
while (resultSet.next()) {
rowData = new HashMap<String, Object>(columnCount);
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnLabel(i), resultSet.getObject(i));
}
break;
} return rowData;
} catch (SQLException e) {
log.error(e.getMessage() + "code = " + e.getErrorCode()+",sql:"+sql);
} finally {
ConnectionFactory.getInstance().closeConnection(connection,preparedStatement, resultSet);
}
return null;
} }
 package com.dl.network_flow.db;

 import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.dl.network_flow.utils.PropertyUtils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/*使用C3P0连接池
* 从C3P0连接池ComboPooledDataSource中获得Connection
* 关闭Connection
* */
public class ConnectionFactory
{ // private static Logger log = Logger.getLogger(ConnectionFactory.class); public static ConnectionFactory connectionFactory = new ConnectionFactory(); private ComboPooledDataSource ds; ///C3P0连接池 ///初始化数据库连接池的参数:5个
///给C3P0连接池指定DriverClass、JdbcUrl、User、Password、InitialPoolSize、MaxPoolSize、CheckoutTimeout
private ConnectionFactory() {
ds = new ComboPooledDataSource();
try {
String DriverClass = PropertyUtils.getValue("DriverClass");
//log.debug("DriverClass = " + DriverClass);
if (DriverClass != null) {
ds.setDriverClass(DriverClass);
}
}
catch (PropertyVetoException e) {
}
String JdbcUrl = PropertyUtils.getValue("JdbcUrl");
//log.debug("JdbcUrl = " + JdbcUrl);
if (JdbcUrl != null) {
ds.setJdbcUrl(JdbcUrl);
} String User = PropertyUtils.getValue("User");
//log.debug("User = " + User);
if (User != null) {
ds.setUser(User);
} String Password = PropertyUtils.getValue("Password");
//log.debug("Password = " + Password);
if (Password != null) {
ds.setPassword(Password);
} String InitialPoolSize = PropertyUtils.getValue("InitialPoolSize");
//log.debug("InitialPoolSize = " + InitialPoolSize);
if (InitialPoolSize != null) {
ds.setInitialPoolSize(Integer.parseInt(InitialPoolSize));
} String MaxPoolSize = PropertyUtils.getValue("MaxPoolSize");
//log.debug("MaxPoolSize = " + MaxPoolSize);
if (MaxPoolSize != null) {
ds.setMaxPoolSize(Integer.parseInt(MaxPoolSize));
} String CheckoutTimeout = PropertyUtils.getValue("CheckoutTimeout");
//log.debug("CheckoutTimeout = " + CheckoutTimeout);
if (CheckoutTimeout != null) {
ds.setCheckoutTimeout(Integer.parseInt(CheckoutTimeout));
} String MaxIdleTime = PropertyUtils.getValue("MaxIdleTime");
if(MaxIdleTime != null){
ds.setMaxIdleTime(Integer.parseInt(MaxIdleTime));
} } public static ConnectionFactory getInstance() {
return connectionFactory;
} /**
* 获得数据库连接
*
* @return
*/
public Connection getConnection() {
try { return ds.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage() + "code = " + e.getErrorCode());
}
} /**
* 关闭数据库连接
*
* @param connection
* @param prepareStatement
* @param resultSet
*/
public void closeConnection(Connection connection, PreparedStatement prepareStatement, ResultSet resultSet) { try {
if (resultSet != null) {
resultSet.close();
}
if (prepareStatement != null) {
prepareStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e.getMessage() + "code = " + e.getErrorCode());
}
} public static void main(String[] args)
{ }
}
 package com.dl.network_flow.utils;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties; /**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 2010-4-23
* Time: 18:02:11
* To change this template use File | Settings | File Templates.
*/
public class PropertyUtils {
private Properties pro = new Properties();
private static PropertyUtils propertyUtils = new PropertyUtils(); private PropertyUtils() {
InputStream in = null;
try {
// pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
in = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
pro.load(bf);
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
} finally {
try {
if(in!=null){
in.close();
}
} catch (IOException e) {
}
}
} public static PropertyUtils getInstance(){
return propertyUtils;
} public static String getValue(String key) {
return (String)getInstance().pro.get(key);
} public static void main(String[] args) throws Exception {
System.out.println(getValue("abcd"));
} }

db.properties 文件内容

#本地
JdbcUrl=jdbc:mysql://IP地址:3306/数据库名称?autoReconnect=true&autoReconnectForPools=true
DriverClass=com.mysql.jdbc.Driver
User=用户名
Password=数据库密码

#初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 initialPoolSize
InitialPoolSize=15

#连接池中保留的最大连接数。Default: 15 maxPoolSize
MaxPoolSize=30
#sp计费信息实时入库,每次入库的数量
spsynCacheSize=30

#最大空闲时间
MaxIdleTime=120

mysql数据库连接工具类C3P0的更多相关文章

  1. 数据库连接工具类——包含取得连接和关闭资源 ConnUtil.java

    package com.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Prepare ...

  2. 数据库连接工具类 数据库连接工具类——仅仅获得连接对象 ConnDB.java

    package com.util; import java.sql.Connection; import java.sql.DriverManager; /** * 数据库连接工具类——仅仅获得连接对 ...

  3. 第一天:java与mysql的连接工具类

    第一天:java与mysql的连接工具类 java最新版马上就要收费,这无疑是这门语言的衰败起始,毕竟在中国收费便难发展,例如c#,但是毕业设计已经选好用java来写一个动态网站, 这已经是一个事实, ...

  4. MySQL数据库工具类之——DataTable批量加入MySQL数据库(Net版)

    MySQL数据库工具类之——DataTable批量加入数据库(Net版),MySqlDbHelper通用类希望能对大家有用,代码如下: using MySql.Data.MySqlClient; us ...

  5. php : mysql数据库操作类演示

    设计目标: 1,该类一实例化,就可以自动连接上mysql数据库: 2,该类可以单独去设定要使用的连接编码(set names XXX) 3,该类可以单独去设定要使用的数据库(use XXX): 4,可 ...

  6. php MySQL数据库操作类源代码

    php MySQL数据库操作类源代码: <?php class MySQL{ private $host; //服务器地址 private $name; //登录账号 private $pwd; ...

  7. PHP - Mysql数据库备份类

    使用方法: require_once("backdata.class.php"); $link =@mysql_connect("localhost",&quo ...

  8. 设计模式 - 单例模式mysql数据库操作类

    待续... index.php 调用方法: <?php header('Content-Type:text/html; charset=utf8'); require 'instance.php ...

  9. C#访问MySQL数据库帮助类

    MySQL数据库访问帮助类 1.项目添加引用官方MySQL动态库MySql.Data.dll 下载地址:MySql.Data.dll(也可以到官网下载动态库)项目添加引用 这里有一个Mysql帮助类的 ...

随机推荐

  1. SDUT 1225-编辑距离(串型dp)

    编辑距离 Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^ 题目描写叙述 如果字符串的基本操作仅为:删除一个字符.插入一个字符和将一个字符改动 ...

  2. cocos2dx项目创建

    射击类游戏文档 作者:浙江传媒学院  新媒体  张勇 1>编译环境 首先我们先去cocos2dx官网上下载cocos2dx最新版本号 http://www.cocos2d-x.org/ 我下载的 ...

  3. ClassNotFoundException和NoClassDefFoundError的差别

    正如它们的名字所说明的:NoClassDefFoundError是一个错误(Error),而ClassNOtFoundException是一个异常,在Java中错误和异常是有差别的,我们能够从异常中恢 ...

  4. 2014年湖北省TI杯大学生电子设计竞赛论文格式

    2014年湖北省TI杯大学生电子设计竞赛 B题:金属物体探測定位器(本科) 2014年8月15日 文件夹 1 系统方案 1.1 XXX的论证与选择........................... ...

  5. [yueqian_scut]Android多点触控技术和应用框架

    Android多点触控技术跟Linux输入子系统紧密相关.本文将从应用的角度说明Android多点触控技术的接口和应用. 一.多点触控场景分析 网络上有关Android多点触控技术的文章多见于两点拉伸 ...

  6. Java做一个时间的程序,为什么要除以1000*60*60*24啊。这个数字是什么意思啊。

    1000耗秒(1秒),60秒(1分),60分(1小时),24小时(1天)

  7. mysql学习 1

    1.数据库(Database)是按照数据结构来组织.存储和管理数据的仓库 2.RDBMS即关系数据库管理系统(Relational Database Management System)的特点: 1) ...

  8. Oracle 合并查询

    8).合并查询有时在实际应用中,为了合并多个select语句的结果,可以使用集合操作符号union,union all,intersect,minus.多用于数据量比较大的数据局库,运行速度快.1). ...

  9. NSRunloop总结

    NSRunloop是一个消息处理机制:是一个循环. 系统通过消息队列和runloop与进程(线程)通信. runloop是一个机制和体系结构. 它包含以下几个方面: 1.事件源管理: 2.事件的检索与 ...

  10. 关于C++程序运行程序是出现的this application has requested the runtime to terminate it in an unusual way. 异常分析

    今天运行程序是出现了this application has requested the runtime  to terminate it in an unusual way. 的异常报告,以前也经常 ...