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)
相关推荐
考虑考虑3 小时前
数据库中的EXISTS
运维·数据库·后端
Wang's Blog3 小时前
Java框架快速入门: Spring Security+OAuth2之数据库和实体类的RBAC改造
java·数据库·spring
梦想平凡4 小时前
百游棋牌源代码开发搭建教程(十):隔离部署、备份恢复与双端验收
java·前端·javascript·数据库·源代码管理
xcLeigh4 小时前
让大模型长出手脚,自己写SQL查数据库(Function Calling初探)
数据库·人工智能·sql·时序数据库·timechoai
yume_sibai5 小时前
06-Rust Web 开发实战(Axum 框架 + 数据库 + JWT 认证 + 中间件 + 部署)
前端·数据库·rust
AugustRed6 小时前
Neo4j 图数据库原理 + 应用场景简单介绍
数据库·neo4j
Gl�ria7 小时前
Redis 高可用架构对比
数据库·redis
IpdataCloud7 小时前
高可用的IP数据接口平台有哪些?从可用性、P99延迟到离线部署的评估框架(含代码)
数据库·tcp/ip·ip
呆萌很7 小时前
MySQL 数据库和表的管理操作(命令行)
数据库·mysql
毕业设计7038 小时前
(免费领源码)基于Python的博物馆研学活动管理系统的设计与实现22724- java、PHP、python、C#、小程序、大数据、单片机、网络工程等)
python·mysql·随机森林·pycharm·django·flask·推荐算法