首頁>技術>

import pymysqlfrom pymysql import Errorclass Db:    __is_begin = None    __db = None    @classmethod    def __connect(cls):        if cls.__db is None:            cls.__db = pymysql.connect(host='127.0.0.1', user='root', password='123456', port=3306, db='test')    @classmethod    def begin(cls):        cls.__connect()        cls.__is_begin = 1    @classmethod    def commit(cls):        cls.__connect()        cls.__db.commit()        cls.__db.close()        cls.__db = None    @classmethod    def rollback(cls):        if cls.__db is not None:            cls.__db.rollback()            cls.__db.close()            cls.__db = None    @classmethod    def insert(cls, table, data):        cls.__connect()        keys = ', '.join(data.keys())        values = ', '.join(['%s'] * len(data))        sql = 'INSERT INTO {table}({keys}) VALUES({values})'.format(table=table, keys=keys, values=values)        try:            if cls.__db.cursor().execute(sql, tuple(data.values())):                insert_id = cls.__db.insert_id()                if cls.__is_begin is None:                    cls.commit()                return insert_id        except Error as e:            cls.rollback()            raise Exception(e.args[0], e.args[1], sql)    @classmethod    def save(cls, table, data):        cls.__connect()        keys = ', '.join(data.keys())        values = ', '.join(['%s'] * len(data))        sql = 'INSERT INTO {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE'.format(table=table, keys=keys,                                                                                             values=values)        update = ','.join([" {key} = %s".format(key=key) for key in data])        sql += update        try:            if cls.__db.cursor().execute(sql, tuple(data.values()) * 2):                if cls.__is_begin is None:                    cls.commit()        except Error as e:            cls.rollback()            raise Exception(e.args[0], e.args[1])    @classmethod    def find(cls, table, where):        cls.__connect()        row = []        for item in where:            row.append(item[0] + item[1] + item[2])        condition = ' and '.join(row)        sql = 'SELECT * FROM {table} WHERE {condition}'.format(table=table, condition=condition)        try:            cls.__db.cursor().execute(sql)            return cls.__db.cursor().fetchone()        except Error as e:            raise Exception(e.args[0], e.args[1])        finally:            cls.__db.close()    @classmethod    def get(cls, table, where={}, limit=10):        cls.__connect()        row = ['1=1']        for item in where:            row.append(item[0] + item[1] + item[2])        condition = ' and '.join(row)        sql = 'SELECT * FROM {table} WHERE {condition} limit {limit}'.format(table=table, condition=condition,                                                                             limit=limit)        try:            cursor = cls.__db.cursor()            cursor.execute(sql)            return cursor.fetchall()        except Error as e:            raise Exception(e.args[0], e.args[1])        finally:            cls.__db.close()

使用方法

from mysql import Db# 新增Db.insert('table',{'name':'hello world','age':100})# 修改或新增Db.save('table',{'id':1,'name':'hello world','age':101})# 查詢Db.find('table',{('id','=','1'),('name','like','%hello%')})

7
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • C++基礎語法梳理:引用、封裝、繼承和多型