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)
相关推荐
BD_Marathon5 小时前
【Flink】部署模式
java·数据库·flink
csudata6 小时前
十年磨一剑,中启乘数CData数据库一体机重新定义企业级数据库解决方案
数据库·数据库开发
TDengine (老段)7 小时前
TDengine IDMP 应用场景:工业锅炉监控
大数据·数据库·物联网·信息可视化·时序数据库·tdengine
dreams_dream9 小时前
Django的Settings 配置文件详解
数据库·django·sqlite
一只叫煤球的猫9 小时前
看到同事设计的表结构我人麻了!聊聊怎么更好去设计数据库表
后端·mysql·面试
遇见你的雩风10 小时前
【MySQL】CRUD基础详解
数据库·mysql
夜雨听萧瑟12 小时前
sqlite创建数据库,创建表,插入数据,查询数据的C++ demo
数据库·sqlite
.Shu.13 小时前
Mysql InnoDB 底层架构设计、功能、原理、源码系列合集【四、事务引擎核心 - MVCC与锁机制】
数据库·mysql
多工坊13 小时前
【DataGrip】连接达梦数据库后,能查询数据但是看不到表的几种情况分析,达梦数据库驱动包下载DmJdbcDriver18.jar
java·数据库·jar
何中应13 小时前
如何用Redis作为消息队列
数据库·redis·缓存