#!/usr/bin/env python2.7
#-*- coding:utf8 -*- import os
import sys
import logging
import MySQLdb from log import Logger logger=Logger("../log/",logging.DEBUG,"mysql_base.log") class MySQLBase(object):
"""MySQLBase""" def __init__(self,host,port,user,passwd,db='',charset='utf8',connect_timeout=1,retry_time=3,use_unicode=1):
self.__host = host
self.__port = port
self.__user = user
self.__passwd = passwd
self.__db = db
self.__charset = charset
self.__connect_timeout = connect_timeout
self.__retry_time = retry_time
self.__use_unicode = use_unicode
self.__connection = self._connection() def _connection(self):
connection = None for i in xrange(0,self.__retry_time):
try:
connection = MySQLdb.connect(host=self.__host,port=int(self.__port),user=self.__user,passwd=self.__passwd,db=self.__db,connect_timeout=self.__connect_timeout,charset=self.__charset,use_unicode=self.__use_unicode)
break
except Exception,e:
if i == self.__retry_time - 1:
message = "Failed to connect to host=%s,port=%s,Error_No:%d,\"%s\"" % (self.__host,self.__port,e[0],str(e[1])) logger.error(message)
print message
#os._exit(1)
exit(1) continue
return connection def cursor(self):
connection = self.__connection cursor = connection.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cursor.execute("set interactive_timeout=28800;")
cursor.execute("set wait_timeout=288000;") return cursor
def close(self):
connection = self.__connection if connection:
connection.close() def main():
host = "127.0.0.1"
port = ""
user = "pt"
passwd="" mysql_base = MySQLBase(host=host,port=port,user=user,passwd=passwd) cursor = mysql_base.cursor() sql = "show databases" cursor.execute(sql) result = cursor.fetchall() for row in result:
print row mysql_base.close()
if __name__ == "__main__":
main()
上述代码对于mysqldb简单封装了一下,更多使用介绍参照