数据库查询语句的封装思路
import yaml def yamlread(path): # 打开并读取YAML文件 with open(path, r, encodingutf-8) as file: config yaml.safe_load(file) return configc创建一个文件操作方法读取文件信息class dboperations: def __init__(self, config_pathrD:\PycharmProjects\PythonProject\config\db.yaml): self.config fileoperation.yamlread(config_path) self.connect None self._auto_commit True property def get_connect(self): 获取连接 dbconfig self.config[database] # 修正正确获取配置参数 self.connect pymysql.connect( hostdbconfig[host], userdbconfig[user], passworddbconfig[password], databasedbconfig[database], charsetutf8mb4, autocommitself._auto_commit ) return self.connect contextmanager def get_cursor(self, cursor_typepymysql.cursors.DictCursor): 上下文管理器自动处理游标和事务 conn self.get_connect cursor conn.cursor(cursor_type) try: yield cursor if self._auto_commit: conn.commit() except Exception as e: conn.rollback() raise e finally: cursor.close() def query_fields_advanced(self, table_name,fields_config,conditionsNone): try: with self.get_cursor() as cursor: sql fSELECT {fields_config} FROM {table_name} if conditions: sql f WHERE {conditions} cursor.execute(sql) results cursor.fetchall() return results except Exception as e: print(f查询失败: {e}) return None def close(self): 关闭连接 if self.connect: self.connect.close() self.connect None创建数据库操作类封装操作动作def debg_quarydata(): # 创建数据库操作对象 db dboperations() table_name db.config[testmessage][tablename] fieldsconfigs db.config[testmessage][fields_config] #将列表转换为数据模式 [a,b]-a,b select_fields ,.join(fieldsconfigs) print(select_fields,table_name) results db.query_fields_advanced(table_name,select_fields) print(results) # 关闭连接 db.close()结果类中进行调用