python 上下文管理 / mysql 连接

连接设计

import pymysql
from utils.parse_json import Jackson
from config.config_file_path import FilePath
from pymysql.util import byte2int


class DB:
    def __init__(self, which_db="testMetaDB", config_file=FilePath.db_config):
        self.source = Jackson.parse_json_file(config_file)[which_db]
        self.conn = pymysql.connect(host=self.source["host"], port=self.source["port"], user=self.source["user"],
                                    password=self.source["password"],
                                    database=self.source["database"], charset="utf8", connect_timeout=10)
        self.cursor = self.conn.cursor()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.conn.close()

    def execute(self, sql: str, args=None):
        self.cursor.execute(sql, args)
        self.conn.commit()

    def executemany(self, sql: str, data: list):
        self.cursor.executemany(sql, data)
        self.conn.commit()

    def fetch_one(self, sql: str, args=None):
        self.cursor.execute(sql, args)
        return self.cursor.fetchone()

    def fetch_all(self, sql: str, args=None):
        self.cursor.execute(sql, args)
        return self.cursor.fetchall()

使用

sql = "select ...."
        with DB() as db:
            return db.fetch_all(sql)

使用 with 的这种方式真爽啊

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,791评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,732评论 19 139
  • 如果此时你难过,那就找个好友倾诉吐槽下,不要想着忍着要坚强,请允许你的脆弱,允许自己发泄后再更加坚强。 “...
    沉金冷玉阅读 1,553评论 0 0
  • 今天胃疼的难受,想起来写写简书。 我是个没有胃病的人,一直以来,胃就特别的健康,吸收特别好,吃什么吸收什么,这……...
    八角苏阅读 2,312评论 0 0
  • 孩子们,再不玩就长大了 在儿童游乐场所,看到一个广告台词,孩子们,再不玩就长大了。大张旗鼓宣传玩,刺激家长出钱让孩...
    舟⼀阅读 3,647评论 0 0