package com.qushida.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
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.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import javax.sql.DataSource; import org.apache.log4j.Logger; import com.mchange.v2.c3p0.ComboPooledDataSource; /**
* 数据库操作辅助类
*
* @version 3.0
* @author xiaocaiji
*/
public class DBUtil {
// 设置数据源(使用C3P0数据库连接池)
private static DataSource dataSource = new ComboPooledDataSource("mysql-config");
private static Logger logger = Logger.getLogger("DBUtil");
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); public static DataSource getDataSource() {
return dataSource;
} // private static Connection conn;
/**
* 该语句必须是 SQL INSERT、UPDATE 、DELETE 语句
*
* @param sql
* @return
* @throws Exception
*/
public int execute(String sql) throws Exception {
return execute(sql, new Object[] {});
} /**
* insert语句使用,返回新增数据的主键。
*
* @param sql
* @return
*/
public Object execute(String sql, Object[] paramList, boolean falg) throws Exception {
Connection conn = null;
Object o = new Object();
try {
conn = getConnection();
o = this.execute(conn, sql, paramList, falg);
} catch (Exception e) {
logger.info(e.getMessage());
throw new Exception(e);
} finally {
closeConn(conn);
}
return o;
} /**
* insert语句使用,返回新增数据的主键。
*
* @param sql
* @return
*/
public Object execute(Connection conn, String sql, Object[] paramList, boolean falg) throws Exception {
if (sql == null || sql.trim().equals("")) {
logger.info("parameter is valid!");
} PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
Object id = null;
try {
// 指定返回生成的主键
// 如果使用静态的SQL,则不需要动态插入参数
setPreparedStatementParam(pstmt, paramList);
if (pstmt == null) {
return -1;
}
pstmt.executeUpdate();
// 检索由于执行此 Statement 对象而创建的所有自动生成的键
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next()) {
id = rs.getObject(1);
System.out.println("数据主键地址:" + id);
}
} catch (Exception e) {
logger.info(e.getMessage());
throw new Exception(e);
} finally {
closeStatement(pstmt);
} return id;
} /**
* 该语句必须是 SQL INSERT、UPDATE 、DELETE 语句 insert into table values(?,?,?,?)
*
* @param sql
* @param paramList:参数,与SQL语句中的占位符一
* @return
* @throws Exception
*/
public int execute(String sql, Object[] paramList) throws Exception {
if (sql == null || sql.trim().equals("")) {
logger.info("parameter is valid!");
} Connection conn = null;
PreparedStatement pstmt = null;
int result = 0;
try {
conn = getConnection();
pstmt = DBUtil.getPreparedStatement(conn, sql);
setPreparedStatementParam(pstmt, paramList);
if (pstmt == null) {
return -1;
}
result = pstmt.executeUpdate();
} catch (Exception e) {
logger.info(e.getMessage());
throw new Exception(e);
} finally {
closeStatement(pstmt);
closeConn(conn);
} return result;
} /**
* 事物处理类
*
* @param connection
* @param sql
* @param paramList:参数,与SQL语句中的占位符一
* @return
* @throws Exception
*/
public int execute(Connection conn, String sql, Object[] paramList) throws Exception {
if (sql == null || sql.trim().equals("")) {
logger.info("parameter is valid!");
} PreparedStatement pstmt = null;
int result = 0;
try {
pstmt = DBUtil.getPreparedStatement(conn, sql);
setPreparedStatementParam(pstmt, paramList);
if (pstmt == null) {
return -1;
}
result = pstmt.executeUpdate();
} catch (Exception e) {
logger.info(e.getMessage());
throw new Exception(e);
} finally {
closeStatement(pstmt);
} return result;
} /**
* 获取实体类型的方法,type为实体类类型。
*
* @param type
* @param sql
* @param paramList
* @return
* @throws Exception
*/
public Object getObject(Class<?> type, String sql, Object[] paramList) throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(type);
Object obj = type.newInstance();
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
Map map = getObject(sql, paramList);
if (map != null) {
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map != null && map.containsKey(propertyName)) {
Object value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value;
try {
descriptor.getWriteMethod().invoke(obj, args);
} catch (Exception e) {
logger.info("检测一下Table列,和实体类属性:" + propertyName + "" + "是否一致,并且是否是" + value.getClass() + "类型");
throw new Exception(
"检测一下Table列,和实体类属性:" + propertyName + "" + "是否一致,并且是否是" + value.getClass() + "类型");
}
}
}
} else {
obj = null;
}
return obj;
} public List<Class<?>> getQueryList(Class<?> type, String sql, Object[] paramList) throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
List<Map<String, Object>> list = getQueryList(sql, paramList);
List beanList = new ArrayList(); for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Map<String, Object> map = (Map<String, Object>) iterator.next();
Object obj = type.newInstance();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map != null && map.containsKey(propertyName)) {
Object value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value;
try {
descriptor.getWriteMethod().invoke(obj, args);
} catch (Exception e) {
logger.info("检测一下Table列,和实体类属性:" + propertyName + "" + "是否一致,并且是否是" + value.getClass() + "类型");
throw new Exception(
"检测一下Table列,和实体类属性:" + propertyName + "" + "是否一致,并且是否是" + value.getClass() + "类型");
}
}
}
beanList.add(obj);
} return beanList;
} /**
* 将查询数据库获得的结果集转换为Map对象
*
* @param sql:查询
* @return
*/
public List<Map<String, Object>> getQueryList(String sql) throws Exception {
return getQueryList(sql, new Object[] {});
} /**
* 将查询数据库获得的结果集转换为Map对象
*
* @param sql:查询
* @param paramList:参数
* @return
*/
public List<Map<String, Object>> getQueryList(String sql, Object[] paramList) throws Exception {
if (sql == null || sql.trim().equals("")) {
logger.info("parameter is valid!");
return null;
} Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Map<String, Object>> queryList = null;
try {
conn = getConnection();
pstmt = DBUtil.getPreparedStatement(conn, sql);
setPreparedStatementParam(pstmt, paramList);
if (pstmt == null) {
return null;
}
rs = getResultSet(pstmt);
queryList = getQueryList(rs);
} catch (RuntimeException e) {
logger.info(e.getMessage());
System.out.println("parameter is valid!");
throw new Exception(e);
} finally {
closeResultSet(rs);
closeStatement(pstmt);
closeConn(conn);
}
return queryList;
} /**
* 分页查询
*
* @param sql
* @param params
* 查询条件参数
* @param page
* 分页信息
* @return
*/
public Page getQueryPage(Class<?> type, String sql, Object[] params, Page page) {
int totalPages = 0; // 页数
Long rows = 0l;// 数据记录数 // 分页工具类
List<Class<?>> list = null;
Map countMap = null;
try {
list = this.getQueryList(type,
sql + " limit " + (page.getCurPage() - 1) * page.getPageNumber() + " , " + page.getPageNumber(),
params);
countMap = this.getObject(" " + "select count(*) c from (" + sql + ") as t ", params);
rows = (Long) countMap.get("c");
// 求余数
if (rows % page.getPageNumber() == 0) {
totalPages = rows.intValue() / page.getPageNumber();
} else {
totalPages = rows.intValue() / page.getPageNumber() + 1;
} page.setRows(rows.intValue());
page.setData(list);
page.setTotalPage(totalPages);
} catch (Exception e) {
e.printStackTrace();
}
return page;
} /**
* 分页查询
*
* @param sql
* @param params
* 查询条件参数
* @param page
* 分页信息
* @return
*/
public Page getQueryPage(String sql, Object[] params, Page page) {
int totalPages = 0; // 页数
Long rows = 0l;// 数据记录数 // 分页工具类
List<Map<String, Object>> list = null;
Map countMap = null;
try {
list = this.getQueryList(
sql + " limit " + (page.getCurPage() - 1) * page.getPageNumber() + " , " + page.getPageNumber(),
params);
countMap = this.getObject(" " + "select count(*) c from (" + sql + ") as t ", params);
rows = (Long) countMap.get("c");
// 求余数
if (rows % page.getPageNumber() == 0) {
totalPages = rows.intValue() / page.getPageNumber();
} else {
totalPages = rows.intValue() / page.getPageNumber() + 1;
} page.setRows(rows.intValue());
page.setData(list);
page.setTotalPage(totalPages);
} catch (Exception e) {
e.printStackTrace();
}
return page;
} /**
* 将查询数据库获得的结果集转换为Map对象
*
* @param sql:查询
* @return
*/
public Map<String, Object> getObject(String sql) throws Exception {
return getObject(sql, new Object[] {});
} /**
* 将查询数据库获得的结果集转换为Map对象
*
* @param sql:查询
* @param paramList:参数
* @return
*/
public Map<String, Object> getObject(String sql, Object[] paramList) throws Exception {
if (sql == null || sql.trim().equals("")) {
logger.info("parameter is valid!");
return null;
} Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Map map = new HashMap<String, Object>();
try {
conn = getConnection();
pstmt = DBUtil.getPreparedStatement(conn, sql);
setPreparedStatementParam(pstmt, paramList);
if (pstmt == null) {
return null;
}
rs = getResultSet(pstmt);
List list = getQueryList(rs);
if (list.isEmpty()) {
return null;
}
map = (HashMap) list.get(0);
} catch (RuntimeException e) {
logger.info(e.getMessage());
logger.info("parameter is valid!");
throw new Exception(e);
} finally {
closeResultSet(rs);
closeStatement(pstmt);
closeConn(conn);
}
return map;
} private static PreparedStatement getPreparedStatement(Connection conn, String sql) throws Exception {
if (conn == null || sql == null || sql.trim().equals("")) {
return null;
}
PreparedStatement pstmt = conn.prepareStatement(sql.trim());
return pstmt;
} private void setPreparedStatementParam(PreparedStatement pstmt, Object[] paramList) throws Exception {
if (pstmt == null || paramList == null) {
return;
}
DateFormat df = DateFormat.getDateTimeInstance();
for (int i = 0; i < paramList.length; i++) {
// -
if (paramList[i] instanceof Integer) {
int paramValue = ((Integer) paramList[i]).intValue();
pstmt.setInt(i + 1, paramValue);
} else if (paramList[i] instanceof Float) {
float paramValue = ((Float) paramList[i]).floatValue();
pstmt.setFloat(i + 1, paramValue);
} else if (paramList[i] instanceof Double) {
double paramValue = ((Double) paramList[i]).doubleValue();
pstmt.setDouble(i + 1, paramValue);
} else if (paramList[i] instanceof Date) {
pstmt.setString(i + 1, df.format((Date) paramList[i]));
} else if (paramList[i] instanceof Long) {
long paramValue = ((Long) paramList[i]).longValue();
pstmt.setLong(i + 1, paramValue);
} else if (paramList[i] instanceof String) {
pstmt.setString(i + 1, (String) paramList[i]);
}
// = pstmt.setObject(i + 1, paramList[i]);
}
return;
} /**
* 获得数据库查询结果集
*
* @param pstmt
* @return
* @throws Exception
*/
private ResultSet getResultSet(PreparedStatement pstmt) throws Exception {
if (pstmt == null) {
return null;
}
ResultSet rs = pstmt.executeQuery();
return rs;
} /**
* @param rs
* @return
* @throws Exception
*/
private List<Map<String, Object>> getQueryList(ResultSet rs) throws Exception {
if (rs == null) {
return null;
}
ResultSetMetaData rsMetaData = rs.getMetaData();
int columnCount = rsMetaData.getColumnCount();
List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
while (rs.next()) {
Map<String, Object> dataMap = new HashMap<String, Object>();
for (int i = 0; i < columnCount; i++) {
dataMap.put(rsMetaData.getColumnLabel(i + 1), rs.getObject(i + 1));
}
dataList.add(dataMap);
}
return dataList;
} /**
* 关闭数据库
*
* @param conn
*/
private void closeConn(Connection conn) {
if (conn == null) {
return;
}
try {
conn.close();
} catch (SQLException e) {
logger.info(e.getMessage());
}
} /**
* 关闭
*
* @param stmt
*/
private void closeStatement(Statement stmt) {
if (stmt == null) {
return;
}
try {
stmt.close();
} catch (SQLException e) {
logger.info(e.getMessage());
}
} /**
* 关闭
*
* @param rs
*/
private void closeResultSet(ResultSet rs) {
if (rs == null) {
return;
}
try {
rs.close();
} catch (SQLException e) {
logger.info(e.getMessage());
}
} /**
* 可以选择三个不同的数据库连接
*
* @param JDBC
* ,JNDI(依赖web容器 DBCP
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
Connection conn = tl.get();
if (conn == null) {
conn = dataSource.getConnection();
}
return conn;
} /*********** 事务处理方法 ************/
/**
* 开启事务
*/
public static void beginTranscation() throws Exception {
Connection conn = tl.get();
if (conn != null) {
logger.info("事务已经开始!");
throw new SQLException("事务已经开始!");
}
conn = dataSource.getConnection();
conn.setAutoCommit(false);
tl.set(conn);
} /**
* 结束事务
*
* @throws SQLException
*/
public static void endTranscation() throws SQLException {
Connection conn = tl.get();
if (conn == null) {
logger.info("当前没有事务!");
throw new SQLException("当前没有事务!");
}
conn.commit();
} /**
* 回滚
*
* @throws SQLException
*/
public static void rollback() throws SQLException {
Connection conn = tl.get();
if (conn == null) {
logger.info("当前没有事务,不能回滚!");
throw new SQLException("当前没有事务,不能回滚!");
}
conn.rollback();
} /**
* 事务处理,关闭资源
*
* @throws SQLException
*/
public static void closeConn() throws SQLException {
Connection conn = tl.get();
if (conn == null) {
logger.info("当前没有连接,不需要关闭Connection。");
throw new SQLException("当前没有连接,不需要关闭Connection。");
}
conn.close();
tl.remove();
} }

  

Java常用工具类之数据库操作辅助类DBUtil.java的更多相关文章

  1. 【转载】C#工具类:FTP操作辅助类FTPHelper

    FTP是一个8位的客户端-服务器协议,能操作任何类型的文件而不需要进一步处理,就像MIME或Unicode一样.可以通过C#中的FtpWebRequest类.NetworkCredential类.We ...

  2. JavaEE-实验一 Java常用工具类编程

    该博客仅专为我的小伙伴提供参考而附加,没空加上代码具体解析,望各位谅解 1.  使用类String类的分割split 将字符串  “Solutions to selected exercises ca ...

  3. java常用工具类(三)

    一.连接数据库的综合类 package com.itjh.javaUtil; import java.sql.Connection; import java.sql.DriverManager; im ...

  4. java常用工具类(二)

    1.FtpUtil package com.itjh.javaUtil; import java.io.File; import java.io.FileOutputStream; import ja ...

  5. java常用工具类(一)

    一.String工具类 package com.mkyong.common; import java.util.ArrayList; import java.util.List; /** * * St ...

  6. java常用工具类(java技术交流群57388149)

    package com.itjh.javaUtil;   import java.util.ArrayList; import java.util.List;   /** * * String工具类. ...

  7. 项目经验分享——Java常用工具类集合 转

    http://blog.csdn.net/xyw591238/article/details/51678525 写在前面     本文涉及的工具类部分是自己编写,另一部分是在项目里收集的.工具类涉及数 ...

  8. JAVA常用工具类汇总

    一.功能方法目录清单: 1.getString(String sSource)的功能是判断参数是否为空,为空返回"",否则返回其值: 2.getString(int iSource ...

  9. [转]Java常用工具类集合

    转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...

随机推荐

  1. interface Part1(接口详解)

    1. 在日常生活中,手机.笔记本电脑.平板电脑等电子产品提供了不同类型的接口用于充电或者连接不同的设备. 不同类型接口的标准不一样,例如电压.尺寸等. 2. 在C#语言中,接口也会定义一种标准,如果需 ...

  2. ubuntu环境下pycharm编译程序import包出错:ImportError: dynamic module does not define init function (init_caffe)

    出错原因是因为pycharm中的python版本不对,比如程序为2.7版本,但是pycharm编解释器为python3,导致出错,去setting改一下版本就行:pycharm>file> ...

  3. requests模块的基本用法

    requests 什么是requests模块 python中封装好的一个基于网络请求的模块 作用 用来模拟浏览器发送请求 环境安装 pip install requests 编码流程 指定 url 发 ...

  4. 为满足中国税改,SAP该如何打SPS

    *****一定要先阅读这个note***** ***** 2736625 - [ZH] 应对2019中国个税改革,SAP系统升级常见问题汇总 **** 1784328 - How to check C ...

  5. node.js 微信开发3-网页授权

    1.配置公众号的自定义菜单,如 { "button":[ { "type":"view", "name":"公 ...

  6. Elasticsearch ES索引

    ES是一个基于RESTful web接口并且构建在Apache Lucene之上的开源分布式搜索引擎. 同时ES还是一个分布式文档数据库,其中每个字段均可被索引,而且每个字段的数据均可被搜索,能够横向 ...

  7. Android笔记(三十三) Android中线程之间的通信(五)Thread、Handle、Looper和MessageQueue

    ThreadLocal 往下看之前,需要了解一下Java的ThreadLocal类,可参考博文: 解密ThreadLocal Looper.Handler和MessageQueue 我们分析一下之前的 ...

  8. Android笔记(九) Android中的布局——框架布局

    框架布局没有任何定位方式,所有的控件都会摆放在布局的左上角. 代码示例: framelayout.xml <?xml version="1.0" encoding=" ...

  9. Android驱动之设备树简介

    目录 一.    设备树简介    2 1.    问题一:为什么需要设备树?    2 ①名词解释:    2 ②DT详细介绍:    2 ③DTS是DT的源文件,描述Device Tree中的设备 ...

  10. [networking][sdn] BGP/EGP/IGP是什么

    引子 这是一个惊悚的故事,胆小的人不要点开.整个故事,是从这张图开始的. 整个图,分左中右三块.左边是tom和他所在的网络.右边是jerry和他所在的网络.这两个网络可以在世界上的任何一个角落.彼此有 ...