MySQL中的开发基于Python的SQL工具类操作数据库简单示例

操作数据库封装SQL工具类的两种方式

  • 为了更方便的实现基于连接池和pymysql 连接数据库,需开发一个sql工具类来让sql操作更简洁
  • 用两张方式来封装SQL工具类

1 )单例模式

封装 db.py 工具类

py 复制代码
import pymysql
from dbutils.pooled_db import PooledDB

class DBHelper(object):
  def __init__(self):
      self.pool = PooledDB(
        creator=pymysql,
        maxconnections=5,
        mincached=2,
        maxcached=3,
        blocking=True,
        setsession=[],
        ping=0,
        host='127.0.0.1',
        port=3306
        user='root',
        password='xxxxx',
        database='userdb',
        charset='utf8'
      )
  
  def get_conn_cursor(self):
    conn = self.pool.connection()
    cursor=conn.cursor(pyymsql.cursors.DictCursor)
    return conn, cursor
  
  def close_conn_cursor(self, *args):
    for item in args:
      item.close()
  
  def exec(self, sql, **kwargs):
    conn, cursor = self.get_conn_cursor()
    cursor.execute(sql, kwargs)
    conn.commit()
    self.close_conn_cursor(conn, cursor)

  def fetch_one(self, sql, **kwargs):
    conn, cursor = self.get_conn_cursor()
    cursor.execute(sql, kwargs)
    result = cursor.fetchone()
    self.cloes_conn_cursor(conn, cursor)
    return result
  
  def fetch_all(self, sql, **kwarrgs):
    conn, cursor = self.get_conn_cursor()
    cursor.execute(sql, kwargs)
    result = cursor.fetchall()
    self.close_conn_cursor(conn, cursor)
  
db = DBHelper()

xxx.py 调用示例

py 复制代码
from db import db

v1 = db.fetch_one("select * from d1")
print(v1)

v2 = db.fetch_one('select * from d1 where id=%(nid)s ', nid=3)
print(v2)

2 ) 上下文管理

基于 with 上下文管理

sql 复制代码
with 获取连接:
  执行sql (执行完毕后,自动将连接交还给连接池)

封装 db_context.py

py 复制代码
import threading
import pymysql
from dbutils.pooled_db import PooledDB

POOL = PooledDB(
  creator=pymysql, # 使用连接数据库的模块
  maxconnections=5,
  mincached=2,
  maxcached=3,
  blocking=True,
  setssion=[],
  ping=0,
  host='127.0.0.1'
  port=3306,
  user='root',
  password='xxxx',
  database='userdb',
  charset='utf8'
)

class Connect(object):
  def __init__(self):
      self.conn = conn = POOL.connection() # 连接
      self.cursor = conn.cursor(pymysql.cursors.DictCursor) # 游标

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

  def exec(self, sql, **kwargs):
      self.cursor.execute(sql, kwargs)
      self.conn.commit()

  def fetch_one(self, sql, **kwargs):
      self.cursor.execute(sql, kwargs)
      result = self.cursor.fetchone()
      return result
  
  def fetch_all(self, sql, **kwargs):
      self.cursor.excute(sql, kwargs)
      result = self.cursor.fetchall()
      return result

yyy.py 调用示例

py 复制代码
from db_context import Connect

### 实例化 对象得到值
with Connect() as obj:
  ret = obj.fetch_one('select * from d1')
  print(ret)

  ret = obj.fetch_one("select * from d1 where id=%(id)s", id=3)
  print(ret)
相关推荐
sinat_383437361 小时前
Laravel 8 中实现错误日志与调试日志分离的完整配置指南
jvm·数据库·python
sunshine8859 小时前
财务RPA的深水区应用:超越自动化,迈向智能决策支持
数据库
efir OONA10 小时前
MySQL数据库误删恢复_mysql 数据 误删
数据库·mysql·adb
zhangchaoxies10 小时前
如何在 Go 中安全复制接口指针所指向的值
jvm·数据库·python
陈陈CHENCHEN11 小时前
【数据库】MySQL 8.0.40 至 8.0.44 RPM 方式升级指南
数据库·mysql
Azhao110611 小时前
一文读懂分享网站模块介绍(附实操教程)
mysql
m0_7349497911 小时前
怎么利用Navicat进行调整备份文件压缩等级_详细配置与操作步骤
jvm·数据库·python
T.i.s11 小时前
番外续2-MIT-BIH Arrhythmia Database
数据库
有味道的男人12 小时前
AI 效率翻倍:对接 1688 拍立淘接口,商品全量信息一键抓取
数据库
m0_7411733312 小时前
如何处理SQL中的NULL值_使用ISNULL或COALESCE函数
jvm·数据库·python