package com.ruoyi.ext.api.db;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class DBImpl
{
    private static final Logger logger = LoggerFactory.getLogger(DBImpl.class);
    private static final Logger errorLogger = LoggerFactory.getLogger(DBImpl.class);
    private DataSource ds_0 = null;
    private String dsType = "";


    private DBImpl(String dsName, DruidDataSource datasource)
    {
        ds_0 = datasource;

    }

    public synchronized static DBImpl getInstance(String dsName,
                                                  DruidDataSource datasource)
    {
        DBImpl impl = new DBImpl(dsName, datasource);
        return impl;
    }










    public Connection getDBCon()
    {
        Connection con = null;
        try
        {
            con = ds_0.getConnection();
            con.setAutoCommit(false);
            return con;
        }
        catch (Exception e)
        {
            errorLogger.error("getDBConnection error:" + e);
            return null;
        }
    }

    public Connection getConE() throws DBException
    {
        Connection con = null;
        try
        {
            con = ds_0.getConnection();
            con.setAutoCommit(false);
            return con;
        }
        catch (Exception e)
        {
            errorLogger.error("getDBConnection error:" + e);
            throw new DBException("", "getDBConnection error:"
                    + e.getMessage(), e);
        }
    }



    public DBResult getDataBySql(String sql)
    {
        Connection con = null;
        con = getDBCon();
        DBResult DBResult = null;

        try
        {
            DBResult = getDataBySqlBase(sql, 0, con, true);
        }
        catch (DBException e)
        {
            DBResult = new DBResult();
            DBResult.setSuccessed(false);
            DBResult.setMessage(e.getMessage());
        }

        return DBResult;
    }

    public DBResult getDataBySql(String sql, Connection con)
    {
        DBResult DBResult = null;

        try
        {
            DBResult = getDataBySqlBase(sql, 0, con, false);
        }
        catch (DBException e)
        {
            DBResult = new DBResult();
            DBResult.setSuccessed(false);
            DBResult.setMessage(e.getMessage());
        }

        return DBResult;
    }

    public DBResult getDataBySqlT(String sql, Connection con)
            throws DBException
    {
        DBResult DBResult = null;

        DBResult = getDataBySqlBase(sql, 0, con, false);

        return DBResult;
    }

    public DBResult getDataBySqlT(String sql) throws DBException
    {
        Connection con = null;
        con = getConE();
        return getDataBySqlBase(sql, 0, con, true);
    }

    public DBResult getDataBySql(String sql, int rowsLimit)
    {
        Connection con = null;
        DBResult DBResult = null;
        con = getDBCon();

        try
        {
            DBResult = getDataBySqlBase(sql, rowsLimit, con, true);
        }
        catch (DBException e)
        {
            DBResult = new DBResult();
            DBResult.setSuccessed(false);
            DBResult.setMessage(e.getMessage());
        }

        return DBResult;
    }

    public DBResult getDataBySqlT(String sql, int rowsLimit)
            throws DBException
    {
        Connection con = null;
        DBResult DBResult = null;
        con = getConE();

        DBResult = getDataBySqlBase(sql, rowsLimit, con, true);

        return DBResult;
    }

    public DBResult getDataBySql(String sql, int rowsLimit, Connection con)
    {
        DBResult DBResult = null;

        try
        {
            DBResult = getDataBySqlBase(sql, rowsLimit, con, false);
        }
        catch (DBException e)
        {
            DBResult = new DBResult();
            DBResult.setSuccessed(false);
            DBResult.setMessage(e.getMessage());
        }

        return DBResult;
    }

    public DBResult getDataBySqlT(String sql, int rowsLimit, Connection con)
            throws DBException
    {
        DBResult DBResult = null;

        DBResult = getDataBySqlBase(sql, rowsLimit, con, false);
        return DBResult;
    }

    private DBResult getDataBySqlBase(String sql, int rowsLimit,
                                          Connection con, boolean conStandAlone) throws DBException
    {
        Statement stat = null;
        ResultSet rs = null;
        DBResult dbResult = new DBResult();
        if  (sql.trim().length()==0)
        {
            return dbResult;
        }
        try
        {
            stat = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_READ_ONLY);

            logger.info("开始执行sql查询" + sql);

            rs = stat.executeQuery(sql);
            logger.info(sql);


            dbResult.pushResultSet(rs);




            return dbResult;
        }
        catch (SQLException sqle)
        {
            errorLogger.error("执行sql查询失败 :" + sqle + sql);
            throw new DBException(sql, "执行sql查询失败 :" + sqle.getMessage(),
                    sqle);
        }
        catch (Exception e)
        {
            errorLogger.error("执行sql查询失败 " + e + sql);
            throw new DBException(sql, "执行sql查询失败 :" + e.getMessage(), e);
        }
        finally
        {
            try
            {
                if (rs != null)
                    rs.close();
                rs = null;
                stat.close();
                stat = null;
                if (conStandAlone)
                {
                    con.close();
                }
            }
            catch (SQLException sqle)
            {

                logger.error(sqle.getMessage());
            }
        }
    }

    public DBResult getDataBySqlPT(String sql, String paramValue)
            throws DBException
    {
        Connection con = getConE();
        return getDataBySqlPBase(sql, null, new String[]{paramValue}, con,
                true);
    }

    public DBResult getDataBySqlPT(String sql, String paramValue, Connection con)
            throws DBException
    {
        return getDataBySqlPBase(sql, null, new String[]{paramValue}, con,
                false);
    }

    public DBResult getDataBySqlPT(String sql, String paramValue[])
            throws DBException
    {
        Connection con = getConE();
        return getDataBySqlPBase(sql, null, paramValue, con, true);
    }

    public DBResult getDataBySqlPT(String sql, String paramValue[],
                                   Connection con) throws DBException
    {
        return getDataBySqlPBase(sql, null, paramValue, con, false);
    }

    public DBResult getDataBySqlPT(String sql, String paramType[],
                                   String paramValue[]) throws DBException
    {
        Connection con = getConE();
        return getDataBySqlPBase(sql, paramType, paramValue, con, true);
    }

    public DBResult getDataBySqlPT(String sql, String paramType[],
                                   String paramValue[], Connection con) throws DBException
    {
        return getDataBySqlPBase(sql, paramType, paramValue, con, false);
    }

    private DBResult getDataBySqlPBase(String sql, String paramType[],
                                           String paramValue[], Connection con, boolean conStandAlone)
            throws DBException
    {



        PreparedStatement stat = null;
        ResultSet rs = null;
        DBResult dResult = new DBResult();
        try
        {
            stat = con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_READ_ONLY);

            logger.info("开始执行sql查询" + sql);

            if (paramType != null)
            {
                for (int i = 0; i < paramValue.length; i++)
                {
                    if (paramType[i].equals("0"))
                        stat.setString(i + 1, paramValue[i]);
                    else if (paramType[i].equals("1"))
                        stat.setInt(i + 1, Integer.parseInt(paramValue[i]));
                    else
                        stat.setString(i + 1, paramValue[i]);
                }
            }
            else
            {
                for (int i = 0; i < paramValue.length; i++)
                {
                    stat.setString(i + 1, paramValue[i]);
                }
            }


            rs = stat.executeQuery();
            logger.info(sql);

            dResult.pushResultSet(rs);





            return dResult;
        }
        catch (SQLException sqle)
        {
            for (int i = 0; i < paramValue.length; i++)
            {
                sql = sql.replaceFirst("[?]", "'" + paramValue[i] + "'");
            }
            errorLogger.error("执行sql查询失败 :" + sqle + sql);
            throw new DBException(sql, "执行sql查询失败 :" + sqle.getMessage(),
                    sqle);
        }
        catch (Exception e)
        {
            errorLogger.error("执行sql查询失败 " + e + sql);
            throw new DBException(sql, "执行sql查询失败 :" + e.getMessage(), e);
        }
        finally
        {
            try
            {
                if (rs != null)
                    rs.close();
                rs = null;
                if (stat != null)
                stat.close();
                stat = null;
                if (conStandAlone)
                {
                    con.close();
                }
            }
            catch (SQLException sqle)
            {
                logger.error(sqle.getMessage());;
            }
        }
    }




    public DBExecResult execQuery(String sql)
    {
        Connection con = null;
        DBExecResult result = null;
        con = getDBCon();

        try
        {
            result = execQueryBase(sql, con, true);
        }
        catch (DBException e)
        {
            result = new DBExecResult();
            result.setSuccessed(false);
            result.setMessage(e.getMessage());
            result.setSqlscript(sql);
        }

        return result;
    }

    public DBExecResult execQueryT(String sql) throws DBException
    {
        Connection con = null;
        DBExecResult result = new DBExecResult();
        con = getConE();

        result = execQueryBase(sql, con, true);

        return result;
    }

    public DBExecResult execQuery(String sql, Connection con)
    {
        DBExecResult result = null;

        try
        {
            result = execQueryBase(sql, con, false);
        }
        catch (DBException e)
        {
            result = new DBExecResult();
            result.setSuccessed(false);
            result.setMessage(e.getMessage());
            result.setSqlscript(sql);
        }

        return result;
    }

    public DBExecResult execQueryT(String sql, Connection con)
            throws DBException
    {
        DBExecResult result = null;
        result = execQueryBase(sql, con, false);

        return result;
    }

    private DBExecResult execQueryPBase(String sql, String paramType[],
                                            String paramValue[], Connection con, boolean conStandAlone)
            throws DBException
    {
        PreparedStatement stat = null;
        DBExecResult result = new DBExecResult();
        try
        {
            con.setAutoCommit(false);
            stat = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            logger.info("执行sql语句:" + sql);

            if (paramType != null)
            {
                for (int i = 0; i < paramValue.length; i++)
                {

                    if (paramValue[i] != null)
                    {
                        if (paramType[i].equals("0"))
                            stat.setString(i + 1, paramValue[i]);
                        else if (paramType[i].equals("1"))
                            stat.setInt(i + 1, Integer.parseInt(paramValue[i]));
                        else
                            stat.setString(i + 1, paramValue[i]);
                    }
                    else
                    {
                        if (paramType[i].equals("0"))
                            stat.setNull(i + 1, Types.VARCHAR);
                        else if (paramType[i].equals("1"))
                            stat.setNull(i + 1, Types.INTEGER);
                        else
                            stat.setNull(i + 1, Types.VARCHAR);

                    }
                }
            }
            else
            {
                for (int i = 0; i < paramValue.length; i++)
                {
                    if (paramValue[i] != null)

                        stat.setString(i + 1, paramValue[i]);
                    else
                        stat.setNull(i + 1, Types.VARCHAR);
                }
            }


            int cnt = stat.executeUpdate();
            logger.info(sql);

            if (conStandAlone)
            {
                con.commit();
            }



            result.setSuccessed(true);
        }
        catch (SQLException sqle)
        {
            for (int i = 0; i < paramValue.length; i++)
            {
                sql = sql.replaceFirst("[?]", "'" + paramValue[i] + "'");
            }

            errorLogger.error("执行sql失败," + sqle + sql);

            if (conStandAlone)
            {
                try
                {
                    con.rollback();
                }
                catch (SQLException sqle2)
                {

                }
            }

            throw new DBException(sql, "执行sql失败:" + sqle.getMessage(),
                    sqle);

        }
        catch (Exception e)
        {
            errorLogger.error("执行sql失败," + e + sql);

            if (conStandAlone)
            {
                try
                {
                    con.rollback();
                }
                catch (SQLException sqle2)
                {

                }
            }

            throw new DBException(sql, "执行sql失败:" + e.getMessage(), e);

        }
        finally
        {
            try
            {
                stat.close();
                stat = null;
            }
            catch (SQLException sqle)
            {

            }

            if (conStandAlone)
            {
                try
                {
                    con.close();
                }
                catch (SQLException e)
                {

                }
            }
        }

        return result;
    }

    private DBExecResult execQueryBase(String sql, Connection con,
                                           boolean conStandAlone) throws DBException
    {
        Statement stat = null;
        DBExecResult result = new DBExecResult();
        try
        {
            con.setAutoCommit(false);
            stat = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            logger.info("执行sql语句:" + sql);

            int cnt = stat.executeUpdate(sql);
            logger.info(sql);

            if (conStandAlone)
            {
                con.commit();
            }


            result.setSuccessed(true);
        }
        catch (SQLException sqle)
        {
            errorLogger.error("执行sql失败," + sqle + sql);

            if (conStandAlone)
            {
                try
                {
                    con.rollback();
                }
                catch (SQLException sqle2)
                {

                }
            }

            throw new DBException(sql, "执行sql失败:" + sqle.getMessage(),
                    sqle);

        }
        catch (Exception e)
        {
            errorLogger.error("执行sql失败," + e + sql);

            if (conStandAlone)
            {
                try
                {
                    con.rollback();
                }
                catch (SQLException sqle2)
                {

                }
            }

            throw new DBException(sql, "执行sql失败:" + e.getMessage(), e);

        }
        finally
        {
            try
            {
                stat.close();
                stat = null;
            }
            catch (SQLException sqle)
            {

            }

            if (conStandAlone)
            {
                try
                {
                    con.close();
                }
                catch (SQLException e)
                {

                }
            }
        }

        return result;
    }

    public DBExecResult execQueryPT(String sql, String paramValue[])
            throws DBException
    {
        Connection con = getConE();
        return execQueryPBase(sql, null, paramValue, con, true);
    }

    public DBExecResult execQueryPT(String sql, String paramValue[],
                                    Connection con) throws DBException
    {
        return execQueryPBase(sql, null, paramValue, con, false);
    }

    public DBExecResult execQueryPT(String sql, String paramType[],
                                    String paramValue[]) throws DBException
    {
        Connection con = getConE();
        return execQueryPBase(sql, paramType, paramValue, con, true);
    }

    public DBExecResult execQueryPT(String sql, String paramType[],
                                    String paramValue[], Connection con) throws DBException
    {
        return execQueryPBase(sql, paramType, paramValue, con, false);
    }


    public DBExecResult execSqlBatch(String sql[])
    {
        Connection con = null;

        DBExecResult result = null;
        con = getDBCon();

        try
        {
            result = execSqlBatchBase(sql, con, true);
        }
        catch (DBException e)
        {
            result = new DBExecResult();
            result.setSuccessed(false);
            result.setMessage(e.getMessage());
            result.setSqlscript(sql);
        }

        return result;
    }

    public DBExecResult execSqlBatchT(String sql[]) throws DBException
    {
        Connection con = null;

        DBExecResult result = null;
        con = getConE();

        result = execSqlBatchBase(sql, con, true);

        return result;
    }

    public DBExecResult execSqlBatch(String sql[], Connection con)
    {
        DBExecResult result = null;

        try
        {
            result = execSqlBatchBase(sql, con, false);
        }
        catch (DBException e)
        {
            result = new DBExecResult();
            result.setSuccessed(false);
            result.setMessage(e.getMessage());
            result.setSqlscript(sql);
        }

        return result;
    }

    public DBExecResult execSqlBatchT(String sql[], Connection con)
            throws DBException
    {
        DBExecResult result = null;

        result = execSqlBatchBase(sql, con, false);

        return result;
    }

    private DBExecResult execSqlBatchBase(String sql[], Connection con,
                                                boolean conStandAlone) throws DBException
    {
        Statement stat = null;
        DBExecResult result = new DBExecResult();
        int i = 0;
        int ecnt = 0;

        try
        {

            con.setAutoCommit(false);
            stat = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            logger.info("开始批量执行sql");
            for (i = 0; i < sql.length; i++)
            {
                if (sql[i] == null)
                    continue;
                if (sql[i].length() <= 0)
                    continue;

                ecnt += stat.executeUpdate(sql[i]);
                logger.info(sql[i]);

            }

            if (conStandAlone)
            {
                con.commit();
            }


            logger.info("批量执行sql成功结束");
            result.setSuccessed(true);
        }
        catch (SQLException sqle)
        {
            errorLogger.error("批量执行sql失败，" + sqle + ",sql:" + sql[i]);

            if (conStandAlone)
            {
                try
                {
                    con.rollback();
                }
                catch (SQLException sqle2)
                {

                }
            }

            throw new DBException("", "批量执行sql失败: " + sqle.getMessage() + ",sql:" + sql[i],
                    sqle);
        }
        catch (Exception e)
        {
            errorLogger.error("批量执行sql失败" + e);
            throw new DBException("", "批量执行sql失败: " + e.getMessage(), e);
        }
        finally
        {
            try
            {
                stat.close();
                stat = null;
            }
            catch (SQLException sqle)
            {

            }

            if (conStandAlone)
            {
                try
                {
                    con.close();
                }
                catch (SQLException e)
                {

                }
            }
        }

        return result;
    }









    public String getDataBySqlToXML(String sql)
    {
        return getDataBySqlToXML(sql, false);
    }

    public String getDataBySqlToXMLForJson(String sql)
    {
        return getDataBySqlToXML(sql, true);
    }

    public String getDataBySqlToXML(String sql, boolean forJson)
    {
        Connection con = null;
        Statement stat = null;
        ResultSet rs = null;
        int fieldCnt = 0;
        String fieldNameList[] = null;
        StringBuffer sb = null;
        String es = forJson ? "\\" : "";
        String sValue = "";

        try
        {
            con = ds_0.getConnection();
            stat = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            logger.info("开始执行sql查询2Xml" + sql);
            rs = stat.executeQuery(sql);
            rs.setFetchSize(500);
            logger.info(sql);

            ResultSetMetaData rsmd = rs.getMetaData();
            fieldCnt = rsmd.getColumnCount();

            fieldNameList = new String[fieldCnt];

            for (int i = 0; i < fieldCnt; i++)
            {
                fieldNameList[i] = rsmd.getColumnName(i + 1).toUpperCase();
            }

            if (!rs.first())
                return "";

            sb = new StringBuffer();
            sb.append("<?xml version=" + es + "\"1.0" + es + "\" encoding="
                    + es + "\"utf-8" + es + "\"?><data>");
            rs.previous();
            while (rs.next())
            {
                sb.append("<r ");
                for (int j = 0; j < fieldCnt; j++)
                {
                    sValue = rs.getString(j + 1);
                    if (sValue == null)
                        sValue = "";
                    sb.append(fieldNameList[j] + "=" + es + "\"" + sValue + es
                            + "\" ");
                }
                sb.append(" />");
            }
            sb.append("</data>");

            return sb.toString();
        }
        catch (SQLException sqle)
        {
            errorLogger.error("执行sql查询2Xml失败 " + sqle + sql);
        }
        catch (Exception e)
        {
            errorLogger.error("执行sql查询2Xml失败 " + e + sql);
        }
        finally
        {
            try
            {
                if (rs != null)
                    rs.close();
                rs = null;
                if (stat != null)
                stat.close();
                stat = null;
                con.close();
            }
            catch (Exception sqle)
            {
                logger.error("执行sql查询2Xml失败 " + sqle.toString());
            }
        }

        return "";
    }

    public DBExecResult exeProcedureWithRetT(String procName, String param[],
                                       String paramType[], String paramDataType[],boolean coniscommit)
            throws DBException
    {
        return exeProcedureWithRetBase(procName, param, paramType, paramDataType, getConE(), coniscommit);
    }

    public DBExecResult exeProcedureWithRetT(String procName, String param[],
                                             String paramType[], String paramDataType[])
            throws DBException
    {
        return exeProcedureWithRetBase(procName, param, paramType, paramDataType, getConE(), true);
    }
    public DBExecResult exeProcedureWithRet(String procName, String param[],
                                            String paramType[], String paramDataType[])
    {
        return exeProcedureWithRet(procName, param, paramType, paramDataType,  true);
    }
    public DBExecResult exeProcedureWithRet(String procName, String param[],
                                      String paramType[], String paramDataType[],boolean coniscommit)
    {
        Connection con = null;
        DBExecResult result = null;

        try
        {
            con = getConE();
            result = exeProcedureWithRetBase(procName, param, paramType,
                    paramDataType, con, coniscommit);
        }
        catch (DBException e)
        {
            result = new DBExecResult();
            result.setSuccessed(false);
            result.setMessage(e.getMessage());
            result.setSqlscript(e.getMsg());
        }

        return result;
    }
    public DBExecResult exeProcedureWithRetBase(String procName, String param[],
                                               String paramType[], String paramDataType[], Connection con ,  boolean coniscommit
                                               ) throws DBException
    {
        String retList[] = null;
        CallableStatement cs = null;
        String sql = "{call " + procName + "(";
        String retStr = "";
        int outValueCount = 0;
        int outIndex = -1;
        DBExecResult result = new DBExecResult();

        if (param == null)
            return result;
        if (param.length <= 0)
            return result;

        try
        {
            for (int i = 0; i < paramType.length; i++)
            {
                if (i < (paramType.length - 1))
                    sql = sql + "?,";
                else
                    sql = sql + "?";
            }

            sql = sql + ")}";

            logger.info("执行存储过程:" + sql);


            con.setAutoCommit(false);
            cs = con.prepareCall(sql);

            for (int j = 0; j < paramType.length; j++)
            {
                if (paramType[j].equals("in") || paramType[j].equals("inout"))
                {
                    if (paramDataType[j].equals("0"))
                    {
                        cs.setString(j + 1, param[j]);
                    }
                    else
                    {
                        cs.setInt(j + 1, Integer.parseInt(param[j]));
                    }
                }
                if (paramType[j].equals("out") || paramType[j].equals("inout"))
                {
                    outValueCount++;
                    if (paramDataType[j].equals("0"))
                        cs.registerOutParameter(j + 1, Types.VARCHAR);
                    else
                        cs.registerOutParameter(j + 1, Types.INTEGER);
                }
            }

            boolean hadResults =cs.execute();

            retList = new String[outValueCount];

            for (int k = 0; k < paramType.length; k++)
            {
                if (paramType[k].equals("out") || paramType[k].equals("inout"))
                {
                    outIndex++;
                    retList[outIndex] = cs.getString(k + 1);
                    retStr = retStr + cs.getString(k + 1);
                }
            }

            logger.info("执行存储过程, 返回值: " + retStr);
            logger.info("执行存储过程成功");

            int i=0;
            while (hadResults) {

                ResultSet rs = cs.getResultSet();
                if (rs != null) {
                    DBResult ret = new DBResult();
                    ret.pushResultSet(rs);
                    result.setDBResult(i,ret);
                    i++;
                }

                hadResults = cs.getMoreResults(); //检查是否存在更多结果集
            }


            result.setSuccessed(true);
            result.setProcResult(retList);

            if (coniscommit)
            {
                con.commit();
            }



        }
        catch (SQLException sqle)
        {
            errorLogger.error("执行存储过程失败，" + sqle + sql);
            if (coniscommit)
            {
                try
                {
                    con.rollback();
                }
                catch (SQLException sqle2)
                {

                }
            }
            throw new DBException(sql, "执行存储过程失败，" + sqle.getMessage(),
                    sqle);
        }
        catch (Exception e)
        {
            errorLogger.error("执行存储过程失败，" + e + sql);
            throw new DBException(sql, "执行存储过程失败，" + e.getMessage(), e);
        }
        finally
        {
            try
            {
                if (cs != null)
                {
                    cs.close();
                    cs = null;
                }

                if (coniscommit)
                {
                    if (con != null)
                    {
                        con.close();
                    }
                }
            }
            catch (SQLException sqle)
            {

            }
        }

        return result;
    }
    public int executeUpdate(String sql, Object[] params) {

        int affectedLine = 0;
        Connection connnection = null;


        PreparedStatement preparedStatement = null;


         CallableStatement callableStatement = null;


         ResultSet resultSet = null;

        try {

            connnection = ds_0.getConnection();

            preparedStatement = connnection.prepareStatement(sql);

            logger.info("执行语句: " + sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {

                   // if (i==2)
                     // preparedStatement.setObject(i + 1, params[i],2004);
                  //  else
                        preparedStatement.setObject(i + 1, params[i]);
                }
            }
            affectedLine = preparedStatement.executeUpdate();
            int autoIncKeyFromApi = -1;
            ResultSet rs = preparedStatement.getGeneratedKeys();                                  // 获取自增主键！
            if (rs.next()) {
                affectedLine = rs.getInt(1);
            }  else {
                       // throw an exception from here
            }
             rs.close();
            rs = null;




        } catch (Exception e) {
            System.out.println(e.getMessage());
            logger.error("执行sql失败 " +e.getMessage());
        } finally {

            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }


            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }


            if (callableStatement != null) {
                try {
                    callableStatement.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }


            if (connnection != null) {
                try {
                    connnection.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
        return affectedLine;
    }






    public List<Object> excuteQuery(String sql, Object[] params) {

        Connection connnection = null;


        PreparedStatement preparedStatement = null;


        CallableStatement callableStatement = null;


        ResultSet resultSet = null;


        ResultSetMetaData rsmd = null;
        int columnCount = 0;
        try {
            connnection = ds_0.getConnection();


            preparedStatement = connnection.prepareStatement(sql);
            logger.info("执行语句: " + sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    preparedStatement.setObject(i + 1, params[i]);
                }
            }


            resultSet = preparedStatement.executeQuery();
            rsmd = resultSet.getMetaData();
            columnCount = rsmd.getColumnCount();
        } catch (SQLException e1) {
            System.out.println(e1.getMessage());
            logger.error("执行sql失败 " +e1.getMessage());
        }


        List<Object> list = new ArrayList<Object>();

        try {

            while (resultSet.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; i++) {
                    map.put(rsmd.getColumnLabel(i), resultSet.getObject(i));
                }
                list.add(map);
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {

            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }


            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }


            if (callableStatement != null) {
                try {
                    callableStatement.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }


            if (connnection != null) {
                try {
                    connnection.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }
        }

        return list;
    }


    public Object excuteQuery(String sql, Object[] params, int outParamPos, int SqlType) {
        Object object = null;
        Connection connnection = null;


        PreparedStatement preparedStatement = null;


        CallableStatement callableStatement = null;


        ResultSet resultSet = null;
        try {
            connnection = ds_0.getConnection();
            logger.info("执行语句: " + sql);
            callableStatement = connnection.prepareCall(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    callableStatement.setObject(i + 1, params[i]);
                }
            }
            callableStatement.registerOutParameter(outParamPos, SqlType);
            callableStatement.execute();
            object = callableStatement.getObject(outParamPos);

        } catch (Exception e) {
            System.out.println(e.getMessage());
            logger.error("执行sql失败 " +e.getMessage());
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }


            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }

            if (callableStatement != null) {
                try {
                    callableStatement.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }


            if (connnection != null) {
                try {
                    connnection.close();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }
        }

        return object;
    }



}
