Python实例之mysql数据库操作简单实例

发布时间:2020-11-06编辑:脚本学堂
本文介绍了python中MySQLdb操作mysql数据库的方法,主要是通过python的DBUtils库、MySQLdb库来实现连接池操作数据库,有需要的朋友参考下。

例子,通过python的DBUtils库、mysqldb/ target=_blank class=infotextkey>MySQLdb库来实现连接池操作数据库

完整代码:
 

复制代码 代码示例:

#!/usr/bin/python
# www.jb200.com

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()