python工作日常:数据库链接 方法封装

拿来即用 下面是代码

import pymysql
import sys

class Config(object):

    @staticmethod
    def get_config(name):
        config = {
            'localhost': {
                'host': '127.0.0.1',
                'user': 'mysql',
                'password': 'mysql',
                'database': 'mysql',
                'port': 3306
            }
        }
        return config[name]


class UseDB(object):

    def __init__(self, name):
        self.__conn = self.build_conn(name)
        self.__cursor = self.__conn.cursor()

    @property
    def conn(self):
        return self.__conn

    def build_conn(self, name):
        try:
            config = Config.get_config(name)
            conn = pymysql.connect(host=config["host"], user=config["user"], passwd=config["password"],
                                   db=config["database"], charset='utf8')
            return conn
        except Exception as e:
            print('Something wrong: %s' % format(e))

    def getData(self, sql, type="all"):
        self.__cursor.execute(sql)
        if type != "all":
            return self.__cursor.fetchone()
        return self.__cursor.fetchall()

    def postData(self, sql):
        try:
            self.__cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()

    def close(self):
        self.conn.close()

class ToExecute(object):

    def __init__(self, db1, db2):
        self.db1 = UseDB(db1)
        self.db2 = UseDB(db2)

    def xxx(self):
        pass

to = ToExecute(db1='',db2='')



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,297评论 25 709
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,472评论 2 59
  • 薄雨初寒香桂陨, 秋风撩窗扰梦人。 梓里妻儿待某归, 立业星城共闲生。
    timooabc阅读 2,924评论 0 0
  • 适与野情惬,千山高复低。 好峰随处改,幽径独行迷。 霜落熊升树,林空鹿饮溪。 人家在何许,云外一声鸡。
    知一书斋阅读 3,526评论 4 9
  • 微信朋友圈的功能曾经一度令人追崇,没有空间与时间的距离,仿佛人与人之间一下子近了。 还记得那天,一个朋友说她在广西...
    一生如燕阅读 2,750评论 1 2