python数据库相关操作

主要是通过python的dbutils库、mysqldb库来实现连接池操作数据库

import mysqldb
from dbutils.pooleddb import pooleddb
class dbhelper(object):
__pool = none
def __init__(self):
self._conn = dbhelper.__getconnection()
self._cursor = self._conn.cursor()
@staticmethod
def __getconnection():
if dbhelper.__pool is none :
__pool = pooleddb(creator = mysqldb,
mincached=1,
maxcached=20,
host = ‘127.0.0.1’,
port = 3306,
user = ‘root’,
passwd = ‘123456’,
db = ‘test’)
return __pool.connection()
def execute(self, sql, parameter=none):
if parameter is none:
self._cursor.execute(sql)
else :
self._cursor.execute(sql, parameter)
def readone(self, sql, parameter=none):
if parameter is none :
count = self._cursor.execute(sql)
else :
count = self._cursor.execute(sql, parameter)
if count > 0:
return self._cursor.fetchone()
else :
return none
def readlist(self, sql, parameter=none):
if parameter is none :
count = self._cursor.execute(sql)
else :
count = self._cursor.execute(sql, parameter)
if count > 0:
return self._cursor.fetchall()
else :
return none
def commint(self):
self._conn.commit()
def close(self):
if self._cursor :
self._cursor.close()
if self._conn :
self._conn.close()

Posted in 未分类

发表评论