59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""数据库连接封装:cursor.description → namedtuple 行对象。
|
||
|
||
为什么不用 DictCursor —— namedtuple 是只读值对象,
|
||
字段访问是属性而非字符串 key,写错字段名立刻 AttributeError,
|
||
且内存更省;对「查出来做数据准备/断言」的测试场景更贴合。)
|
||
|
||
Demo 默认不连真 MySQL:未配置 MES_DB_HOST 时使用 dao.fake_db.FakeDB,
|
||
接口与 pymysql 连接对象对齐(cursor / commit / rollback / close)。
|
||
"""
|
||
import os
|
||
from collections import namedtuple
|
||
|
||
|
||
def _connect():
|
||
host = os.environ.get('MES_DB_HOST')
|
||
if host:
|
||
import pymysql # 仅在显式配置真实库时才需要
|
||
return pymysql.connect(
|
||
host=host,
|
||
port=int(os.environ.get('MES_DB_PORT', '3306')),
|
||
user=os.environ.get('MES_DB_USER', ''),
|
||
password=os.environ.get('MES_DB_PASS', ''),
|
||
database=os.environ.get('MES_DB_NAME', ''),
|
||
charset='utf8',
|
||
)
|
||
from dao.fake_db import FakeDB
|
||
return FakeDB()
|
||
|
||
|
||
class DBConn:
|
||
"""查询返回 namedtuple 行对象列表;写操作 commit / 异常 rollback。"""
|
||
|
||
def __init__(self):
|
||
self.conn = _connect()
|
||
self.cursor = self.conn.cursor()
|
||
|
||
def select(self, sql, params=None):
|
||
result = []
|
||
self.cursor.execute(sql, params)
|
||
# 从 cursor.description 取字段名
|
||
keys = [d[0] for d in self.cursor.description]
|
||
Row = namedtuple('Row', keys)
|
||
for row in self.cursor.fetchall():
|
||
result.append(Row(*row))
|
||
return result
|
||
|
||
def execute(self, sql, params=None):
|
||
try:
|
||
self.cursor.execute(sql, params)
|
||
self.conn.commit()
|
||
except Exception as e:
|
||
self.conn.rollback()
|
||
raise e
|
||
|
||
def close(self):
|
||
self.cursor.close()
|
||
self.conn.close()
|