#encoding:utf-8#name:mod_db.py
'''
使用方法:1.在主程序中先实例化DB Mysql数据库操作类。
2.使用方法:db=database() db.fetch_all("sql")
'''
importMySQLdbimportMySQLdb.cursorsimportmod_configimportmod_logger
DB= "database"LOGPATH= mod_config.getConfig('path', 'logpath') + 'database.log'DBNAME= mod_config.getConfig(DB, 'dbname')
DBHOST= mod_config.getConfig(DB, 'dbhost')
DBUSER= mod_config.getConfig(DB, 'dbuser')
DBPWD= mod_config.getConfig(DB, 'dbpassword')
DBCHARSET= mod_config.getConfig(DB, 'dbcharset')
DBPORT= mod_config.getConfig(DB, "dbport")
logger=mod_logger.logger(LOGPATH)
#数据库操作类classdatabase:
#注,python的self等于其它语言的thisdef __init__(self, dbname=None, dbhost=None):
self._logger=logger
#这里的None相当于其它语言的NULLif dbname isNone:
self._dbname=DBNAMEelse:
self._dbname=dbnameif dbhost isNone:
self._dbhost=DBHOSTelse:
self._dbhost=dbhost
self._dbuser=DBUSER
self._dbpassword=DBPWD
self._dbcharset=DBCHARSET
self._dbport=int(DBPORT)
self._conn=self.connectMySQL()if(self._conn):
self._cursor=self._conn.cursor()#数据库连接
defconnectMySQL(self):
conn=Falsetry:
conn= MySQLdb.connect(host=self._dbhost,
user=self._dbuser,
passwd=self._dbpassword,
db=self._dbname,
port=self._dbport,
cursorclass=MySQLdb.cursors.DictCursor,
charset=self._dbcharset,
)exceptException,data:
self._logger.error("connect database failed, %s" %data)
conn=Falsereturnconn#获取查询结果集
deffetch_all(self, sql):
res= ''
if(self._conn):try:
self._cursor.execute(sql)
res=self._cursor.fetchall()exceptException, data:
res=False
self._logger.warn("query database exception, %s" %data)returnresdefupdate(self, sql):
flag=Falseif(self._conn):try:
self._cursor.execute(sql)
self._conn.commit()
flag=TrueexceptException, data:
flag=False
self._logger.warn("update database exception, %s" %data)returnflag#关闭数据库连接
defclose(self):if(self._conn):try:if(type(self._cursor)=='object'):
self._cursor.close()if(type(self._conn)=='object'):
self._conn.close()exceptException, data:
self._logger.warn("close database exception, %s,%s,%s" % (data, type(self._cursor), type(self._conn)))