package com.xing.mooc.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.sql.Types;
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 org.apache.log4j.Logger;
/**
* 数据库操作辅助类
* @version 3.0
* @author yaohc
*/
public class DBUtil {
private static Logger logger = Logger.getLogger("DBUtil");
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
//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;
if (null != 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;
if (null != 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 (RuntimeExcept