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. robot framework环境配置

    1.Robot framework的安装 作用:web自动化测试框架. RF框架是基于python 的,所以一定要有python环境.网上可以自行查找. 下载地址:https://pypi.pytho ...

  2. Nagios监控nginx服务具体过程

    1在nginx 服务器上安装nrpe客户端: Nginx的服务须要监控起来.不然万一down了而不及时修复,会影响web应用.例如以下web应用上面启动的nginx后台进程[root@lb-net-2 ...

  3. 自醒的觉悟与力量——leo鉴书59

    30岁之后由于看得书多起来,阅读和写作也都有了自己的套路,与此相对的写书评之前须要看几遍书,然后我才干下笔的作者和作品越来越少了. 崔卫平是这种作者,而<正义之前>是我看了两遍才開始写评的 ...

  4. EM无法登录,提示ORA-28001: the password has expired (DBD ERROR: OCISessionBegin)

    --查看数据库目前的口令期限 sys@TESTDB11>select * from dba_profiles where profile = 'DEFAULT' and resource_nam ...

  5. ROS-turtlesim

    前言:turtlesim是ros自带的一个功能包,应该是用于基础教学的功能包,帮助新手入门的一个实例,包括:节点,主题,服务以及参数的应用.通过学习使用turtlesim功能包可以了解ros的一些基础 ...

  6. BZOJ 4358 坑 莫队+线段树 死T

    这是一个坑 竟然卡nsqrt(n)logn T死 等更 //By SiriusRen #include <cmath> #include <cstdio> #include & ...

  7. HDU4920 矩阵乘法

    嗯嗯 就算是水题吧. (缩完行就15行) 题意:两个n*n的矩阵相乘(n<=800),结果对3取模 思路:先对3取模,所以两个矩阵里面会出现很多0,所以可以先枚举一个矩阵,只有当该位置不是0的时 ...

  8. centOS 7安装mysql5.6

    方法二:官网下载安装mysql-server # wget http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm # rp ...

  9. Hybrid混合开发中schema协议的使用与封装

    混合开发中JS与APP通信的实现原理: JS通过schema协议,传递参数和全局回调函数给APP端 APP执行完(如微信扫一扫)后,调用协议中传入的回调函数,在前端执行回调处理. 默认写法: < ...

  10. Golden Gate 概述

    概述: 是什么?Oracle GoldenGate 提供异构环境间事务数据的实时.低影响的捕获.路由.转换和交付. 非侵入: 不建触发器,不建中间表,无需增量标记或时间戳字段 不在源表上进行数据查询 ...