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. docker第二章--数据管理

  2. iOS - 毛玻璃特效

    iOS7.0的SDK并没有提供给开发者实现毛玻璃效果的API,所以很多人都是通过一些别人封装的框架来实现 iOS7.0(包括)之前还是有系统的类可以实现毛玻璃效果的, 就是 UIToolbar这个类, ...

  3. iOS - Objective-C 关联(objc_setAssociatedObject、objc_getAssociatedObject、objc_removeAssociatedObjects)

    关联是指把两个对象相互关联起来,使得其中的一个对象作为另外一个对象的一部分. 关联特性只有在Mac OS X V10.6以及以后的版本上才是可用的. 在类的定义之外为类增加额外的存储空间 使用关联,我 ...

  4. 【转载】常见面试题:C#中String和string的区别分析

    在很多人面试C#开发工程师的时候,会遇到一个面试题,就是C#中String和string有啥区别.其实针对这个问题C#中String和string没有本质上的区别,两者在程序中都可使用,稍微的一个区别 ...

  5. python的excel处理之openpyxl

    一.颜色处理 cell = sheet.cell(row, col)font = Font(size=12, bold=False, name='Arial', color=colors.BLACK) ...

  6. node.js 接口调用示例

    测试用例git地址(node.js部分):https://github.com/wuyongxian20/node-api.git 项目架构如下: controllers: 文件夹下为接口文件 log ...

  7. 在浏览器中输入www.taobao.com后执行的全部过程

    >>>点击网址后,应用层的DNS协议会将网址解析为IP地址: DNS查找过程: 1.        浏览器会检查缓存中有没有这个域名对应的解析过的IP地址,如果缓存中有,这个解析过程 ...

  8. 【leetcode】366.Find Leaves of Binary Tree

    原题 Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all lea ...

  9. git使用方法(持续更新)

    2018/5/9 最基本的操作: 添加文件.文件夹.所有文件: git add test.py   //添加单个文件 git add src        //添加文件夹 git add .      ...

  10. 【DevOps】在Rancher2中启动Docker-Registry仓库服务

    准备 拥有Rancher2环境,已经在Rancher2配置Kubernetes集群 拥有域名,拥有SSL证书,可以自行在阿里云申请 启动Docker-Registry仓库服务 第一步:进入集群应用 第 ...