標籤:python blog github dbutils
這個Utils用了第三方庫DBUtils,我經過又一層了簡單封裝,自認為還是挺簡潔的,只實現了增刪改查
import MySQLdb,functoolsfrom DBUtils.PooledDB import PooledDBimport sys reload(sys) sys.setdefaultencoding('utf-8') sys.path.append('../')import readConfig __author__='xiezhaodong at 2014-8-14'class Mysql(object):'''This method can get the connection pool and a connection object'''conn=None__pool=Nonedef __init__(self):self.__pool=self.__initPool()self.conn=self.getConn()@staticmethoddef __initPool():'''A static method cannot access the instance variables'''if Mysql.__pool is None:try:print 'install pool'__pool=PooledDB(creator=MySQLdb,maxusage=readConfig.maxusage,mincached=readConfig.mincached,maxcached=readConfig.maxcached, db=readConfig.db, host=readConfig.host, user=readConfig.user, passwd=readConfig.passwd, charset=readConfig.charset,port=readConfig.port)return __poolexcept Exception,e :print 'create pool default',ereturn Nonedef getConn(self):'''Get a link from the connection pool'''#print 'get connection from pool'if self.__pool is None:return Nonereturn self.__pool.connection()init=Mysql()class _ConnetionCtx(object):'''Ctx get connection and exit close connectioncan user with _ConnetionCtx():''' def __enter__(self):global initself.mysql=init#Load the MySQL object get linksself.conn=Noneself.clean=Falseif self.conn is None:#print 'connect'self.conn=self.mysql.getConn()self.clean=True#print self.conn,'---------connection'return selfdef __exit__(self,exc_type,exc_value,traceback):if self.conn is not None and self.clean is True:'''Release the connection object'''#print 'close conn'self.conn.close()self.conn=Nonedef ConnectionCtxController(func):'''decorator to get connection and release connectionThe CTX parameter passed to the function'''@functools.wraps(func)def _wrapper(**args):with _ConnetionCtx() as Ctx:return func(Ctx=Ctx,**args)return _wrapper@ConnectionCtxControllerdef select(Ctx,sql,kw):'''get select rowsReturns None if the said no database links, return () said there is no corresponding data'''sql=sql.replace('?','%s')conn=Ctx.connresult=Noneif conn is None:'''no conn'''return Noneelse:'''have conn'''try:cur=conn.cursor()cur.execute(sql,kw)result=cur.fetchall()except Exception ,e:print 'select default',ereturn Nonefinally:cur.close()return result@ConnectionCtxControllerdef CRUDExceptSelect(Ctx,sql,kw,batch=False):'''This method can add, delete, modify, the default batch is False if True will use batch SQL statements, the return value is None for no connection or the SQL is abnormal, the other back value represents the number of successful execution'''sql=sql.replace('?','%s')conn=Ctx.connrow_succcess=Noneif conn is None:return Noneelse:cur=Nonetry:cur=conn.cursor()if batch:row_succcess=cur.executemany(sql,kw)else:row_succcess=cur.execute(sql,kw)except Exception, e:conn.rollback()print 'insetr default',efinally:if cur is not None:print 'close cur'cur.close()conn.commit()#return row_succcess
github地址:https://github.com/xiexiaodong/blog/blob/master/python-db.py
config
[db] db_host=sqld.duapp.comdb_port=4050db_user=youruserdb_pass=yourpasswordmaxusage=10mincached=10maxcached=100db=uWKDOxUdHCujVdsrCjjYcharset=utf8[concurrent] thread=10 processor=20
readconfig
import ConfigParser,string,os,sys'''reload config'''class config(object):def __init__(self,path='./config.ini'):self.path=pathself.cf=ConfigParser.ConfigParser()#print self.cf,'cf'try:self.cf.read(self.path)self.section=self.cf.sections()except Exception,e:print e,'exception read'#print 'start',self.sectiondef get(self,field,key):result=''try:result=self.cf.get(field,key)except Exception,e:print e,'2'result=''return resultdef getint(self,field,key):result=''try:result=self.cf.getint(field,key)except Exception,e:print e,'2'result=''return resultconfig=config()host=config.get('db','db_host')port=config.getint('db','db_port')user=config.get('db','db_user')passwd=config.get('db','db_pass')maxusage=config.getint('db','maxusage')mincached=config.getint('db','mincached')maxcached=config.getint('db','maxcached')db=config.get('db','db')charset=config.get('db','charset')
自己封裝的python——DBUtilS,大家多多指教