Python database related operations

巴扎黑
Release: 2016-12-08 10:39:02
Original
1293 people have browsed it

Mainly through python’s DBUtils library and MySQLdb library to implement connection pool operation database

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()
Copy after login

                                                                                                                                                        

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template