# encoding:utf8
import ConfigParser
import sys
import os
# import MySQLdb
# import logging
from sqlalchemy import create_engine

reload(sys)
sys.setdefaultencoding('utf8')

# logging.basicConfig(level=logging.INFO,
#                     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
#                     datefmt='%a, %d %b %Y %H:%M:%S',
#                     filename='sql.log',
#                     filemode='a+')

# console = logging.StreamHandler()
# logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
# formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# console.setFormatter(formatter)
# logging.getLogger('sqlalchemy.engine').addHandler(console)

#
# class db_connect():
#     def __init__(self, db, db_name):
#         """
#         给出数据库名字，创建数据库连接
#         :param db:要连接的数据库，可选值（xyqb ,diting, offline, paycenter, mall, local, lkbadmin, lkbpayment）
#         :param db_name:要连接的数据库中的库名
#         """
#         self.cf = ConfigParser.ConfigParser()
#         self.cf.read('D:/workspace/duizhang/duizhang_script/api/config.ini')
#         host = self.cf.get(db, 'host')
#         user = self.cf.get(db, 'user')
#         passwd = self.cf.get(db, 'passwd')
#         port = int(self.cf.get(db, 'port'))
#         self.__conn = MySQLdb.connect(host=host, user=user, passwd=passwd, port=port, charset='utf8', db=db_name)
#         self.__cursor = self.__conn.cursor()
#
#     def get_conn(self):
#         """
#         获取数据库连接
#         :return: 数据库连接
#         """
#         return self.__conn


class sql_engine():
    def __init__(self, db, db_name=None, echo=True):
        """
        给出数据库名字，创建数据库连接
        :param db:
        :param db_name:
        :param echo:
        """
        self.cf = ConfigParser.ConfigParser()
        self.cf.read(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'config.ini'))
        host = self.cf.get(db, 'host')
        user = self.cf.get(db, 'user')
        passwd = self.cf.get(db, 'passwd')
        port = int(self.cf.get(db, 'port'))
        if not db_name:
            db_name = self.cf.get(db, 'db')
        self.__engine = create_engine('mysql+mysqldb://%s:%s@%s:%s/%s?charset=utf8' % (user, passwd, host, port, db_name), echo=echo)

    def get_engine(self):
        return self.__engine

if __name__ == '__main__':
    import pandas as pd
    engine = sql_engine('local', 'test').get_engine()
    result = engine.execute('select biz_type, plan_id, repay_type, record_id, ref_amount from repay_plan_repay_record_ref limit 10;')
    df = pd.DataFrame(data=list(result), columns=['biz_type', 'plan_id', 'repay_type', 'record_id', 'ref_amount'])

    print df.head()