# -*- coding: UTF-8 -*-
import MySQLdb
from os import path
import os
import sys
from DBUtils.PooledDB import PooledDB
from frame import logger
from pyutil.idc.idc import get_idc
from config import db_config
basedir = path.realpath(path.join(path.dirname(__file__), '..'))
sys.path.append(basedir)
reload(sys)
env = os.environ.get('IS_TCE_ENV')
if env is not None and env == 'YES' :
DB_Config = db_config.Fcdn_Live_DBConf_Tce
logger.info('DB_Config=%s', DB_Config)
logger.info('current env is: %s', env)
else:
DB_Config = db_config.Fcdn_Live_DBConf_Boe
logger.info('DB_Config=%s', DB_Config)
logger.info('current env is: %s', env)
#10为连接池里的最少连接数
POOL = PooledDB(MySQLdb, mincached=10, blocking=True, host = DB_Config['host'],user =DB_Config['user'], passwd = DB_Config['passwd'],
db =DB_Config['db'], port = DB_Config['port'],charset='utf8')
class DBHelper(object):
# 后面添加类名作为参数,然后返回类实例,方便后面处理
def select(self, sql):
conn = POOL.connection()
cursor = conn.cursor()
try:
# 执行SQL语句
logger.info("sql: %s", sql)
cursor.execute(sql)
allResult = cursor.fetchall()
column_names = []
for item in cursor.description:
column_names.append(item[0])
if len(allResult) <= 0:
return None, None
return tuple(column_names), allResult
except Exception as e:
logger.info(e.message + e.args ,exc_info=1)
logger.error("Error: unable to fetch data")
return None, None
finally:
# 关闭数据库连接
cursor.close()
conn.close()
# 插入数据库
def insert(self, sql):
conn = POOL.connection()
cursor = conn.cursor()
try:
# 执行SQL语句
logger.info("sql: %s", sql)
cursor.execute(sql)
conn.commit()
except Exception as e:
logger.info(e.message + e.args ,exc_info=1)
logger.error("Error: unable to insert data")
conn.rollback()
finally:
# 关闭数据库连接
cursor.close()
conn.close()
# 更新数据库
def update(self, sql):
conn = POOL.connection()
cursor = conn.cursor()
try:
# 执行SQL语句
logger.info("sql: %s", sql)
cursor.execute(sql)
conn.commit()
except Exception as e:
logger.info(e.message + e.args ,exc_info=1)
logger.error("Error: unable to update data")
conn.rollback()
finally:
# 关闭数据库连接
cursor.close()
conn.close()
if __name__ == '__main__':
logger.info('DB_Config=%s',DB_Config)