baseDao
package com.uugty.common.dao;
import java.lang.reflect.Field;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
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.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import com.uugty.common.constant.StringConstant;
import com.uugty.common.domain.ResponseEntity;
import com.uugty.common.utils.BeanUtil;
import com.uugty.common.utils.DateUtil;
import com.uugty.common.utils.EasemobUtil;
import com.uugty.common.utils.JdbcUtil;
import com.uugty.common.utils.NumberUtil;
import com.uugty.common.utils.RedisUtil;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
/**
* @author yusq
*/
public class BaseDao {
private static final Logger log = Logger.getLogger(BaseDao.class);
/**
* 获取数据库连接
*
* @return
*/
@SuppressWarnings("static-access")
public Connection openConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection("proxool.myData");
//conn =JdbcUtil.getConnection();
} catch (SQLException e) {
try {
Thread.currentThread().sleep(500);
conn = DriverManager.getConnection("proxool.myData");
} catch (Exception e1) {
try {
Thread.currentThread().sleep(500);
conn = DriverManager.getConnection("proxool.myData");
} catch (Exception e2) {
throw new RuntimeException("数据库连接失败", e2);
}
}
}
return conn;
}
/**
* 关闭数据库资源
*
* @param ps
* @param st
* @param rs
* @param conn
*/
public void close(PreparedStatement ps, Statement st, ResultSet rs, Connection conn) {
try {
if (ps != null) {
ps.close();
}
} catch (Exception e) {
log.error("关闭PreparedStatement异常异常!", e);
throw new RuntimeException("关闭PreparedStatement异常异常!", e);
} finally {
try {
if (st != null) {
st.close();
}
} catch (Exception e1) {
log.error("关闭Statement异常!", e1);
throw new RuntimeException("关闭Statement异常!", e1);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (Exception e1) {
log.error("关闭ResultSet异常!", e1);
throw new RuntimeException("关闭ResultSet异常!", e1);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (Exception e1) {
log.error("关闭连接异常!", e1);
throw new RuntimeException("关闭连接异常!", e1);
} finally {
}
}
}
}
}
public <T> T getBean(Class<T> cla, ResultSet rs, ResultSetMetaData metaData)
throws InstantiationException, IllegalAccessException, SecurityException, SQLException {
Field[] fields = cla.getDeclaredFields();
T t = cla.newInstance();
for (int i = 0; i < metaData.getColumnCount(); i++) {
String columnName = metaData.getColumnLabel(i + 1);
// 将字段名称和字段值封装到bean对象中去
for (Field field : fields) {
field.setAccessible(true);
String fieldName = field.getName();
// 将表的"_"去除
String pureColumnName = columnName.replace("_", "");
if (fieldName.equalsIgnoreCase(pureColumnName)) {
Class<?> clazzField = field.getType();
if ("price".equals(fieldName) || "openPrice".equals(fieldName)
|| "buyMaxPrice".equals(fieldName) || "sellMinPrice".equals(fieldName)
|| "positionMarketValue".equals(fieldName) || "bookingTimeValue".equals(fieldName)) {
//如果是这几个字段,封装的时候自动除以100
field.set(t,NumberUtil.getDivPrice(rs.getString(columnName)));
}
else if (clazzField == String.class) {
field.set(t, rs.getString(columnName));
} else if (clazzField == short.class || clazzField == Short.class) {
field.setShort(t, rs.getShort(columnName));
} else if (clazzField == int.class || clazzField == Integer.class) {
field.setInt(t, rs.getInt(columnName));
} else if (clazzField == long.class || clazzField == Long.class) {
field.setLong(t, rs.getLong(columnName));
} else if (clazzField == float.class || clazzField == Float.class) {
field.setFloat(t, rs.getFloat(columnName));
} else if (clazzField == double.class || clazzField == Double.class) {
field.setDouble(t, rs.getDouble(columnName));
} else if (clazzField == boolean.class || clazzField == Boolean.class) {
field.setBoolean(t, rs.getBoolean(columnName));
} else if (clazzField == byte.class || clazzField == Byte.class) {
field.setByte(t, rs.getByte(columnName));
} else if (clazzField == char.class || clazzField == Character.class) {
field.set(t, rs.getCharacterStream(columnName));
} else if (clazzField == Date.class) {
field.set(t, rs.getTimestamp(columnName));
} else if (clazzField.isArray()) {
field.set(t, rs.getString(columnName).split(",")); // 以逗号分隔的字符串
} else {
field.set(t, rs.getObject(columnName));
}
}
}
}
return t;
}
/**
* 向数据库添加数据
*
* @param sql
* @param list
* @return 自增的主键
*/
public int insertReturnKey(String sql, List<Object> list) throws Exception {
log(sql, list);
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
conn = openConnection();
pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
pst.setString(i + 1, list.get(i) != null ? list.get(i).toString() : "");
}
}
pst.executeUpdate();
rs = pst.getGeneratedKeys();
rs.next();
return rs.getInt(1);
} finally {
close(pst, null, rs, conn);
}
}
/**
* @param sql
* @param list
* @throws SQLException
* @return 受影响行数
*/
public int insert(String sql, List<Object> list) throws SQLException {
log(sql, list);
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
conn = openConnection();
pst = conn.prepareStatement(sql);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
pst.setString(i + 1, list.get(i) != null ? list.get(i).toString() : "");
}
}
return pst.executeUpdate();
} finally {
close(pst, null, rs, conn);
}
}
/**
* 更新数据库数据
*
* @param sql
* @param args
* @return
* @throws SQLException
*/
public boolean update(String sql, List<Object> args) throws SQLException {
log(sql, args);
PreparedStatement ps = null;
Connection conn = null;
try {
conn = openConnection();
ps = conn.prepareStatement(sql);
if (args != null && args.size() > 0) {
for (int i = 0; i < args.size(); i++) {
ps.setObject(i + 1, args.get(i));
}
}
return ps.execute();
} finally {
close(ps, null, null, conn);
}
}
/**
* 修改数据库数据
*
* @param sql
* @param args
* @return 受影响行数
* @throws SQLException
*/
public int executeUpdate(String sql, List<Object> args) throws SQLException {
log(sql, args);
PreparedStatement ps = null;
Connection conn = null;
try {
conn = openConnection();
ps = conn.prepareStatement(sql);
if (args != null && args.size() > 0) {
for (int i = 0; i < args.size(); i++) {
ps.setObject(i + 1, args.get(i));
}
}
return ps.executeUpdate();
} finally {
close(ps, null, null, conn);
}
}
/**
* 删除数据库数据
*
* @param sql
* @param args
* @return
* @throws SQLException
*/
public void delete(String sql, List<Object> args) throws SQLException {
log(sql, args);
PreparedStatement ps = null;
Connection conn = null;
try {
conn = openConnection();
ps = conn.prepareStatement(sql);
if (args != null && args.size() > 0) {
for (int i = 0; i < args.size(); i++) {
ps.setObject(i + 1, args.get(i));
}
}
ps.executeUpdate();
} finally {
close(ps, null, null, conn);
}
}
/**
* 执行存储过程
*
* @param sql
* @param args
* @return
* @throws SQLException
*/
public List<Object[]> execProcs(String sql, List<Object> args) throws SQLException {
log(sql, args);
List<Object[]> list = new ArrayList<Object[]>();
CallableStatement cs = null;
ResultSet rs = null;
Connection conn = null;
try {
conn = openConnection();
cs = conn.prepareCall(sql);
if (args != null) {
for (int i = 0; i < args.size(); i++) {
cs.setObject(i + 1, args.get(i));
}
}
if (cs.execute()) {
rs = cs.getResultSet();
while (rs.next()) {
int count = rs.getMetaData().getColumnCount();
Object[] obj = new Object[count];
for (int i = 0; i < count; i++) {
obj[i] = rs.getObject(i + 1);
}
list.add(obj);
}
}
return list;
} finally {
cs.close();
close(null, null, rs, conn);
}
}
/**
* 执行带输出参数存储过程
*
* @param sql
* @param args
* @return
* @throws SQLException
*/
public String execProcsWithOut(String sql, List<Object> args, String outParameter) throws SQLException {
log(sql, args);
List<Object[]> list = new ArrayList<Object[]>();
CallableStatement cs = null;
ResultSet rs = null;
Connection conn = null;
try {
conn = openConnection();
cs = conn.prepareCall(sql);
if (null != args && args.size() > 0) {
for (int i = 0; i < args.size(); i++) {
cs.setObject(i + 1, args.get(i));
}
cs.registerOutParameter(args.size() + 1, Types.VARCHAR);
}
try {
/*
* if ( cs.execute ( ) ) { rs = cs.getResultSet ( ); while (
* rs.next ( ) ) { int count = rs.getMetaData ( ).getColumnCount
* ( ); Object [ ] obj = new Object [ count ]; for ( int i = 0 ;
* i < count ; i ++ ) { obj [ i ] = rs.getObject ( i + 1 ); }
* list.add ( obj ); } }
*/
cs.execute();
return cs.getString(args.size() + 1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} finally {
if (null != cs) {
cs.close();
}
close(null, null, rs, conn);
}
}
/**
* 查询数量
*
* @param sql
* @param args
* @return
* @throws SQLException
*/
public int count(String sql, List<Object> args) throws SQLException {
log(sql, args);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
int count = 0;
try {
conn = openConnection();
ps = conn.prepareStatement(sql);
if (args != null) {
for (int i = 0; i < args.size(); i++) {
ps.setObject(i + 1, args.get(i));
}
}
rs = ps.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
} finally {
close(ps, null, rs, conn);
}
return count;
}
/**
* 向数据库添加数据
*
* @param sql
* @param list
* @return
*/
public int executeInsert ( String sql , List < Object > list ) throws Exception
{
log ( sql , list );
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try
{
conn = openConnection ( );
pst = conn.prepareStatement ( sql , Statement.RETURN_GENERATED_KEYS );
if ( list != null )
{
for ( int i = 0 ; i < list.size ( ) ; i ++ )
{
pst.setString ( i + 1 , list.get ( i ) != null ? list.get ( i ).toString ( ) : "" );
}
}
pst.executeUpdate ( );
rs = pst.getGeneratedKeys ( );
rs.next ( );
return rs.getInt ( 1 );
}
finally
{
close ( pst , null , rs , conn );
}
}
/**
* @throws SQLException
* @Title: query @Description: 查询数据库数据 @param @param
* sql @param @param args @param @return @return List<Object[]>
* 返回类型 @throws
*/
public List<Object[]> query(String sql, List<Object> args) throws SQLException {
log(sql, args);
Connection conn = openConnection();
PreparedStatement ps = conn.prepareStatement(sql);
if (args != null) {
for (int i = 0; i < args.size(); i++) {
ps.setObject(i + 1, args.get(i));
}
}
ResultSet rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
List<Object[]> lists = new ArrayList<Object[]>();
int count = metaData.getColumnCount();
if (rs != null && !rs.isClosed()) {
while (rs.next()) {
Object[] obj = new Object[count];
for (int i = 0; i < count; i++) {
obj[i] = rs.getObject(i + 1);
}
lists.add(obj);
}
}
close(ps, null, rs, conn);
return lists;
}
/**
* @throws IllegalAccessException
* @throws InstantiationException @throws SQLException @Title:
* query @Description: 查询数据库数据,并封装数据 @param @param sql
* sql查询语句 @param @param args 查询参数 @param @param cla
* 字节码文件 @param @return @return List<Object> 返回类型 @throws
*/
@SuppressWarnings("rawtypes")
public <T> List<T> query(String sql, List<Object> args, Class<T> cla)
throws SQLException, InstantiationException, IllegalAccessException {
log(sql, args);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = openConnection();
// conn=JdbcUtil.getConnection ( );
ps = conn.prepareStatement(sql);
if (args != null) {
for (int i = 0; i < args.size(); i++) {
ps.setObject(i + 1, args.get(i));
}
}
List<T> list = new ArrayList<T>();
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
if (rs != null && !rs.isClosed()) {
while (rs.next()) {
T t = getBean(cla, rs, metaData);
list.add(t);
}
}
return list;
} finally {
close(ps, null, rs, conn);
}
}
public List<Object> queryList(String sql, List<Object> args)
throws SQLException, InstantiationException, IllegalAccessException {
log(sql, args);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
List<Object> lists = new ArrayList<Object>();
conn = openConnection();
ps = conn.prepareStatement(sql);
if (args != null) {
for (int i = 0; i < args.size(); i++) {
ps.setObject(i + 1, args.get(i));
}
}
rs = ps.executeQuery();
if (rs != null && !rs.isClosed()) {
while (rs.next()) {
lists.add(rs.getObject(1));
}
}
return lists;
} finally {
close(ps, null, rs, conn);
}
}
/**
* @throws IllegalAccessException
* @throws InstantiationException @throws SQLException @Title:
* getBeanList @Description: 将数据库查询出来的结果封装到对象的集合中去 @param @param
* cla @param @param lists @param @param
* metaData @param @return @return List<Object> 返回类型 @throws
*/
@SuppressWarnings("rawtypes")
public List<Object> getBeanList(Class cla, List<Object[]> lists, ResultSetMetaData metaData)
throws SQLException, InstantiationException, IllegalAccessException {
List<Object> list = new ArrayList<Object>();
Field[] fields = BeanUtil.getFileds(cla);
for (Object[] objects : lists) {
Object bean = cla.newInstance();
for (int i = 0; i < metaData.getColumnCount(); i++) {
String columnName = metaData.getColumnLabel(i + 1);
// String columnName = metaData.getColumnName(i + 1);
String columnValue = String.valueOf(objects[i]);
// 将字段名称和字段值封装到bean对象中去
for (Field field : fields) {
field.setAccessible(true);
String fieldName = field.getName();
// 将表的"_"去除
columnName = columnName.replace("_", "");
if (fieldName.equalsIgnoreCase(columnName)) {
if ("price".equals(fieldName) || "openPrice".equals(fieldName)
|| "buyMaxPrice".equals(fieldName) || "sellMinPrice".equals(fieldName)
|| "positionMarketValue".equals(fieldName) || "bookingTimeValue".equals(fieldName)) {
if (null != objects[i] && !"".equals(objects[i])) {
columnValue = NumberUtil.getDivPrice(objects[i].toString());
}
}
if ("miaochatTime".equals(fieldName)) {
if (null != objects[i] && !"".equals(objects[i])) {
columnValue = DateUtil.showTime(objects[i].toString());
}
}
BeanUtil.setProperty(field, bean, columnValue);
break;
}
}
}
list.add(bean);
}
return list;
}
public <T> List<T> getBeanList(Class<T> cla, ResultSet rs)
throws SQLException, InstantiationException, IllegalAccessException {
List<T> list = new ArrayList<T>();
if (rs != null) {
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
T t = getBean(cla, rs, metaData);
list.add(t);
}
}
return list;
}
/**
* @throws SQLException
* @Title: executeInsertBatch @Description: 批处理添加 @param @param
* sql @param @param lists @param @return @return int[]
* 主键id @throws
*/
public int[] executeInsertBatch(String sql, List<List<Object>> lists) throws SQLException {
for (List<Object> list : lists) {
log(sql, list);
}
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
int[] ids = new int[lists.size()];
int count = 0;
try {
conn = openConnection();
pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for (List<Object> list : lists) {
for (int i = 0; i < list.size(); i++) {
pst.setString(i + 1, list.get(i) != null ? list.get(i).toString() : "");
}
pst.addBatch();
}
pst.executeBatch();
rs = pst.getGeneratedKeys();
while (rs != null && rs.next()) {
ids[count] = rs.getInt(1);
count++;
}
return ids;
} finally {
close(pst, null, rs, conn);
}
}
/**
* @Title: log @Description: 打印出sql和参数 @param @param sql @param @param
* list @return void 返回类型 @throws
*/
public static void log(String sql, List<Object> list) {
StringBuffer buffer = new StringBuffer();
if (list != null && list.size() > 0) {
for (Object object : list) {
buffer.append(object + StringConstant.QUOTA);
}
log.error("SQL:" + sql + "参数:" + buffer.toString() + "---------------" );
}
}
@SuppressWarnings("rawtypes")
public List<Object> query2(String sql, List<Object> args, Class cla)
throws SQLException, InstantiationException, IllegalAccessException {
log(sql, args);
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql);
if (args != null) {
for (int i = 0; i < args.size(); i++) {
ps.setObject(i + 1, args.get(i));
}
}
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
List<Object[]> lists = new ArrayList<Object[]>();
int count = metaData.getColumnCount();
if (rs != null && !rs.isClosed()) {
while (rs.next()) {
Object[] obj = new Object[count];
for (int i = 0; i < count; i++) {
obj[i] = rs.getObject(i + 1);
}
lists.add(obj);
}
}
List<Object> list = getBeanList(cla, lists, metaData);
return list;
} finally {
close(ps, null, rs, conn);
}
}
/**
* 对需要进行一个原子操作的sql挨个执行,若其中一个执行失败,则所有sql执行失败
*
* @param sql
* 要执行的sql集合
* @param args
* 每个sql对应的参数设置值
* @return 执行结果
*/
@SuppressWarnings("resource")
public boolean asyncExecute(List<String> sql, List<List<Object>> args) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = openConnection();
conn.setAutoCommit(false);
try {
for (int i = 0; i < sql.size(); i++) {
ps = conn.prepareStatement(sql.get(i));
for (int j = 0; j < args.get(i).size(); j++) {
ps.setObject(j + 1, args.get(i).get(j));
}
if (ps.execute()) {
throw new Exception();
}
}
conn.commit();
return true;
} catch (Exception e) {
conn.rollback();
return false;
} finally {
close(ps, null, null, null);
}
} catch (SQLException e) {
return false;
} finally {
close(null, null, null, conn);
}
}
//清仓处理逻辑 买+收入-卖-消费
//方法逻辑:通过清仓公式算出某个用户持有的某个房屋是否为0,如果为0说明清仓,1该用户该房屋之前清仓过,修改清仓时间;2该用户该房屋之前没有清仓过新增清仓时间
public boolean queryActualNumberAndUpdateClearance(int investorsCode, String userId, String date) {
boolean flag = false;
Connection conn = null;
PreparedStatement pst = null;
PreparedStatement pst2 = null;
PreparedStatement pst3 = null;
// PreparedStatement pst32 = null;
ResultSet rs = null;
ResultSet rs2 = null;
String sql = "";
int actualNumber = 2;
int i = 0;
conn = openConnection();
try {
/*
* sql =
* "SELECT aa.buyer_actual_number-IFNULL(bb.seller_actual_number,0) AS actualNumber FROM (SELECT investors_code,SUM(buyer_actual_number)AS buyer_actual_number FROM (SELECT buyer_actual_number,investors_code FROM t_buyer_order_record where user_id=? AND investors_code="
* + investorsCode +
* " AND buyer_order_status=2 UNION ALL SELECT IFNULL(buyer_actual_number,0),investors_code FROM t_buyer_success_order where user_id=? AND investors_code="
* + investorsCode +
* " )AS aa)AS aa LEFT JOIN (SELECT b.investors_code,SUM(b.seller_actual_number) AS seller_actual_number FROM (SELECT seller_actual_number,investors_code FROM t_seller_order_record where user_id=? AND investors_code="
* + investorsCode +
* " AND seller_order_status=2 UNION ALL SELECT ifnull(seller_actual_number,0) as seller_actual_number,investors_code FROM t_seller_success_order where user_id=? AND investors_code="
* + investorsCode +
* " )AS b)AS bb ON aa.investors_code=bb.investors_code";
*/
sql = "SELECT " + investorsCode
+ " AS investors_code, SUM(positionnum) AS actualNumber FROM ( SELECT buyer_actual_number AS positionnum FROM t_buyer_order_record WHERE user_id =? AND investors_code = "
+ investorsCode
+ " AND buyer_order_status = 2 UNION ALL SELECT IFNULL(buyer_actual_number, 0) AS positionnum FROM t_buyer_success_order WHERE user_id =? AND investors_code = "
+ investorsCode
+ " UNION ALL SELECT IFNULL(income_order_num, 0) AS positionnum FROM t_consume_order_income t WHERE t.income_user_id =? AND t.investors_code = "
+ investorsCode
+ " AND t.order_status = 2 UNION ALL SELECT 0 - seller_actual_number AS positionnum FROM t_seller_order_record WHERE user_id =? AND investors_code = "
+ investorsCode
+ " AND seller_order_status = 2 UNION ALL SELECT 0 - IFNULL(seller_actual_number, 0) AS positionnum FROM t_seller_success_order WHERE user_id = ? AND investors_code = "
+ investorsCode
+ " UNION ALL SELECT 0 - IFNULL(t2.consume_order_num, 0) AS positionnum FROM t_consume_order t2 WHERE t2.buy_user_id = ? AND t2.investors_code = "
+ investorsCode + " AND t2.consume_order_status = 2 ) AS aa";
pst = conn.prepareStatement(sql);
pst.setString(1, userId);
pst.setString(2, userId);
pst.setString(3, userId);
pst.setString(4, userId);
pst.setString(5, userId);
pst.setString(6, userId);
rs = pst.executeQuery();
log.info(sql + "参数:{" + userId + "," + userId + "," + userId + "," + userId + "," + userId + "," + userId
+ "}");
if (rs.next()) {
actualNumber = rs.getInt("actualNumber");
}
log.info("========================actualNumber=" + actualNumber);
if (actualNumber == 0) {
flag = true;
sql = "SELECT 1 FROM t_seller_clearance WHERE user_id=? AND investors_code=" + investorsCode;
pst2 = conn.prepareStatement(sql);
pst2.setString(1, userId);
log.info(sql + "参数:{" + userId + "}");
rs2 = pst2.executeQuery();
if (rs2.next()) {
i = rs2.getInt(1);
}
if (i == 1) {
if (null != date && !"".equals(date)) {
sql = "UPDATE t_seller_clearance SET clearance_date=? WHERE user_id=? AND investors_code="
+ investorsCode;
pst3 = conn.prepareStatement(sql);
pst3.setString(1, date);
pst3.setString(2, userId);
log.info(sql + "参数:{" + date + "," + userId + "}");
pst3.executeUpdate();
} else {
sql = "UPDATE t_seller_clearance SET clearance_date=now(3) WHERE user_id=? AND investors_code="
+ investorsCode;
pst3 = conn.prepareStatement(sql);
pst3.setString(1, userId);
log.info(sql + "参数:{" + userId + "}");
pst3.executeUpdate();
}
} else {
if (null != date && !"".equals(date)) {
sql = "INSERT INTO t_seller_clearance(user_id,investors_code,clearance_date) VALUES(?,?,?)";
pst3 = conn.prepareStatement(sql);
pst3.setString(1, userId);
pst3.setInt(2, investorsCode);
pst3.setString(3, date);
log.info(sql + "参数:{" + userId + "," + investorsCode + "," + date + "}");
pst3.executeUpdate();
} else {
sql = "INSERT INTO t_seller_clearance(user_id,investors_code,clearance_date) VALUES(?,?,now(3))";
pst3 = conn.prepareStatement(sql);
pst3.setString(1, userId);
pst3.setInt(2, investorsCode);
log.info(sql + "参数:{" + userId + "," + investorsCode + "}");
pst3.executeUpdate();
}
}
/*
* sql =
* "DELETE FROM t_user_investors WHERE user_id=? AND investors_code="
* + investorsCode; pst32 = conn.prepareStatement ( sql );
* pst32.setString ( 1 , userId); log.info ( sql + "参数:{" +
* userId+ "}" ); pst32.executeUpdate ( );
*/
}
} catch (SQLException e) {
log.error("更新清仓日期出现异常!", e);
throw new RuntimeException("更新清仓日期出现异常!", e);
} finally {
try {
/*
* if ( null != pst32 && ! pst32.isClosed ( ) ) { pst32.close (
* ); }
*/
if (null != pst3 && !pst3.isClosed()) {
pst3.close();
}
if (null != pst2 && !pst2.isClosed()) {
pst2.close();
}
if (null != rs2 && !rs2.isClosed()) {
rs2.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
close(pst, null, rs, conn);
}
return flag;
}
//测试方法
public void queryActualNumberAndUpdateClearance(int investorsCode, String userId, Timestamp sellerActualDate) {
Connection conn = null;
PreparedStatement pst = null;
PreparedStatement pst2 = null;
PreparedStatement pst3 = null;
ResultSet rs = null;
ResultSet rs2 = null;
String sql = "";
int actualNumber = 2;
int i = 0;
conn = openConnection();
Calendar cal = Calendar.getInstance();
cal.setTime(sellerActualDate);
try {
sql = "SELECT (SUM(aa.buyerActualNumber)-SUM(bb.sellerActualNumber))AS actualNumber FROM (SELECT SUM(cc.buyerActualNumber) AS buyerActualNumber FROM (SELECT buyer_actual_number AS buyerActualNumber FROM t_buyer_order_record WHERE investors_code="
+ investorsCode
+ " AND user_id=? AND buyer_order_status=2 and buyer_actual_date<=? UNION ALL SELECT buyer_actual_number AS buyerActualNumber FROM t_buyer_order_record_his WHERE investors_code="
+ investorsCode
+ " AND user_id=? AND buyer_order_status=2 and buyer_actual_date<=?)AS cc)AS aa,(SELECT SUM(dd.sellerActualNumber)AS sellerActualNumber FROM (SELECT seller_actual_number AS sellerActualNumber FROM t_seller_order_record WHERE investors_code="
+ investorsCode
+ " AND user_id=? AND seller_order_status=2 and seller_actual_date<=? UNION ALL SELECT seller_actual_number AS sellerActualNumber FROM t_seller_order_record_his WHERE investors_code="
+ investorsCode
+ " AND user_id=? AND seller_order_status=2 and seller_actual_date<=?) AS dd)AS bb";
pst = conn.prepareStatement(sql);
pst.setString(1, userId);
pst.setTimestamp(2, sellerActualDate);
pst.setString(3, userId);
pst.setTimestamp(4, sellerActualDate);
pst.setString(5, userId);
pst.setTimestamp(6, sellerActualDate);
pst.setString(7, userId);
pst.setTimestamp(8, sellerActualDate);
rs = pst.executeQuery();
// log.info ( sql + "参数:{" + userId + "," + userId + "," + userId +
// "," + userId + "}" );
if (rs.next()) {
actualNumber = rs.getInt("actualNumber");
}
// log.info ( "========================actualNumber=" + actualNumber
// );
if (actualNumber == 0) {
sql = "SELECT 1 FROM t_seller_clearance_copy WHERE user_id=? AND investors_code=" + investorsCode;
pst2 = conn.prepareStatement(sql);
pst2.setString(1, userId);
log.info(sql + "参数:{" + userId + "}");
rs2 = pst2.executeQuery();
if (rs2.next()) {
i = rs2.getInt(1);
}
if (i == 1) {
sql = "UPDATE t_seller_clearance_copy SET clearance_date=? WHERE user_id=? AND investors_code="
+ investorsCode;
pst3 = conn.prepareStatement(sql);
pst3.setString(1, userId);
pst3.setTimestamp(2, sellerActualDate);
log.info(sql + "参数:{" + userId + "}");
pst3.execute();
} else {
sql = "INSERT INTO t_seller_clearance_copy(user_id,investors_code,clearance_date) VALUES(?,?,?)";
pst3 = conn.prepareStatement(sql);
pst3.setString(1, userId);
pst3.setInt(2, investorsCode);
pst3.setTimestamp(3, sellerActualDate);
// log.info ( sql + "参数:{" + userId + "," + investorsCode +
// "}" );
pst3.execute();
}
}
} catch (SQLException e) {
log.error("更新清仓日期出现异常!", e);
throw new RuntimeException("更新清仓日期出现异常!", e);
} finally {
try {
if (null != pst3) {
pst3.close();
}
if (null != pst2) {
pst2.close();
}
if (null != rs2) {
rs2.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
close(pst, null, rs, conn);
}
}
/**
* <p>
* Title: saveMiaoNotice
* </p>
* <p>
* Description: 保存通知并建立跟用户关联关系
* </p>
*
* @author yangyang
* @param title
* @param content
* @param investorsCode
* @param investorsName
*/
public void saveMiaoNotice(String title, String content, int investorsCode, String investorsName, String userId) {
Connection conn = null;
PreparedStatement pst = null;
PreparedStatement pst2 = null;
PreparedStatement pst3 = null;
PreparedStatement pst5 = null;
ResultSet rs = null;
ResultSet rs2 = null;
String sql = "";
String sql2 = "";
conn = openConnection();
int notice_id = 0;
StringBuilder builder = new StringBuilder();
int num = 0;
try {
conn.setAutoCommit(false);// 开启事务
sql = "INSERT INTO t_notice(investors_code,notice_title,notice_content,notice_status,notice_create_date) VALUES(?,?,?,?,NOW())";
pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pst.setInt(1, investorsCode);
pst.setString(2, title);
pst.setString(3, content);
pst.setInt(4, 1);
log.info(sql + "参数:{ " + investorsCode + "," + title + "," + content + "," + 1 + "}");
pst.executeUpdate();
rs = pst.getGeneratedKeys();
if (rs.next()) {
notice_id = rs.getInt(1);
}
if (null == userId || "".equals(userId)) {
sql = "SELECT user_id FROM (SELECT aa.user_id,SUM(buyer_actual_number) AS num FROM ( SELECT buyer_actual_number, investors_code, user_id FROM t_buyer_order_record WHERE investors_code = "
+ investorsCode
+ " AND buyer_order_status = 2 UNION ALL SELECT IFNULL(buyer_actual_number, 0) AS buyer_actual_number, investors_code, user_id FROM t_buyer_success_order WHERE investors_code = "
+ investorsCode
+ " UNION ALL SELECT IFNULL(income_order_num, 0) AS buyer_actual_number, investors_code, income_user_id AS user_id FROM t_consume_order_income WHERE investors_code = "
+ investorsCode
+ " AND order_status = 2 UNION ALL SELECT 1 AS buyer_actual_number, investors_code, user_id FROM t_user_investors WHERE investors_code = "
+ investorsCode
+ " UNION ALL SELECT - seller_actual_number AS buyer_actual_number, investors_code, user_id FROM t_seller_order_record WHERE investors_code = "
+ investorsCode
+ " AND seller_order_status = 2 UNION ALL SELECT - ifnull(seller_actual_number, 0) AS buyer_actual_number, investors_code, user_id FROM t_seller_success_order WHERE investors_code = "
+ investorsCode
+ " UNION ALL SELECT - IFNULL(consume_order_num, 0) AS buyer_actual_number, investors_code, buy_user_id AS user_id FROM t_consume_order WHERE investors_code ="
+ investorsCode
+ " AND (consume_order_status = 2 or consume_order_status=9)) AS aa GROUP BY aa.user_id)AS bb WHERE bb.num > 0";
pst2 = conn.prepareStatement(sql);
log.info("sql=" + sql);
rs2 = pst2.executeQuery();
while (rs2.next()) {
String user_id = rs2.getString(1);
builder.append("(" + notice_id + "," + "'" + user_id + "'" + ")" + ",");
num++;
if (num >= 500) {
sql2 = "INSERT INTO t_notice_user(notice_id,user_id) VALUES"
+ builder.deleteCharAt(builder.length() - 1);
pst3 = conn.prepareStatement(sql2);
log.info("1269sql2=" + sql2);
pst3.executeUpdate();
log.info("通知用户关联num=" + num);
if (builder.length() > 0) {
builder.delete(0, builder.length());
num = 0;
}
}
}
log.info("剩余不足100通知用户关联num=" + num);
if (num > 0) {
sql = "INSERT INTO t_notice_user(notice_id,user_id) VALUES"
+ builder.deleteCharAt(builder.length() - 1);
pst5 = conn.prepareStatement(sql);
log.info("1285sql=" + sql);
pst5.executeUpdate();
log.info("通知用户关联num=" + num);
if (builder.length() > 0) {
builder.delete(0, builder.length());
num = 0;
}
}
} else {
sql = "INSERT INTO t_notice_user(notice_id,user_id) VALUES(?,?)";
pst5 = conn.prepareStatement(sql);
pst5.setInt(1, notice_id);
pst5.setString(2, userId);
log.info("sql=" + sql);
pst5.executeUpdate();
}
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
log.error("保存通知并建立跟用户关联关系回滚出现异常!", e);
throw new RuntimeException("保存通知并建立跟用户关联关系回滚出现异常!", e);
}
log.error("保存通知并建立跟用户关联关系出现异常!", e);
throw new RuntimeException("保存通知并建立跟用户关联关系出现异常!", e);
} finally {
try {
if (null != pst5 && !pst5.isClosed()) {
pst5.close();
}
if (null != pst3 && !pst3.isClosed()) {
pst3.close();
}
if (null != pst2 && !pst2.isClosed()) {
pst2.close();
}
if (null != rs2 && !rs2.isClosed()) {
rs2.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
close(pst, null, rs, conn);
}
}
/**
* 向数据库插入数据,返回影响行数
*
*/
public int insertAndReturn(String sql, List<Object> list) throws Exception {
log(sql, list);
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
conn = openConnection();
pst = conn.prepareStatement(sql);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
pst.setString(i + 1, list.get(i) != null ? list.get(i).toString() : "");
}
}
int result = pst.executeUpdate();
return result;
} finally {
close(pst, null, rs, conn);
}
}
}