网站首页 > 技术文章 正文
引言:
DBConnector 类的目的是提供一个简洁且可扩展的数据库连接管理工具。它封装了与数据库交互的常见操作,比如执行查询、插入、更新、删除等,并且支持异步执行查询任务。
代码封装如下:
其中 self.config 配置的是数据库连接信息, 这里直接填写了对应的信息(测试需要这里使用了此方法)。 也可通过读取配置文件来使变量参数化(推荐)
import os
import pymssql
from concurrent.futures import ThreadPoolExecutor
class DBConnector:
def __init__(self, config=None):
# 配置数据库连接信息
self.config = config
self.connection = None # 单一数据库连接
self.setup_connection() # 初始化连接
def setup_connection(self):
"""初始化数据库连接"""
try:
self.connection = pymssql.connect(
server=self.config.get('host'),
user=self.config.get('user'),
password=self.config.get('password'),
database=self.config.get('db'),
charset='cp936',
as_dict=True
)
except Exception as e:
print(f"连接数据库失败: {e}")
raise e
def execute_query(self, query, params=None):
"""执行更新、删除、插入等非SELECT查询"""
if not self.connection:
print("数据库连接尚未建立")
return None
try:
with self.connection.cursor() as cursor:
cursor.execute(query, params)
self.connection.commit()
except Exception as e:
print(f"执行查询失败: {e}")
raise e
def fetch_query(self, query, params=None):
"""执行SELECT查询并返回结果"""
if not self.connection:
print("数据库连接尚未建立")
return None
try:
with self.connection.cursor() as cursor:
cursor.execute(query, params)
results = cursor.fetchall()
return results
except Exception as e:
print(f"执行查询失败: {e}")
raise e
def determine_query_type(self, query):
"""自动判断查询类型"""
query_upper = query.strip().upper()
if query_upper.startswith("SELECT"):
return 'fetch'
else:
return 'execute'
def async_execute(self, query, params=None):
"""异步执行SQL查询"""
query_type = self.determine_query_type(query)
results = []
with ThreadPoolExecutor() as executor:
futures = []
if query_type == 'fetch':
futures.append(executor.submit(self.fetch_query, query, params))
else:
futures.append(executor.submit(self.execute_query, query, params))
for future in futures:
try:
result = future.result()
if result is not None:
results.append(result)
except Exception as e:
print(f"执行任务失败: {e}")
return results # 返回所有查询的结果
'''async_execute 仍然可以并行执行查询,但因为只有一个连接,'''
'''所以实际上不会并行查询多个数据库。这里只是简化了异步操作的结构,保证可以继续用于未来扩展,或者在需要的情况下并行执行其他操作。'''
if __name__ == "__main__":
# 示例:连接到数据库并执行查询
config = { 'host': '数据库ip', 'user': '用户名', 'password': '密码', 'db': '库名', 'charset': 'utf-8' }
connector = DBConnector(config)
# 执行更新操作(插入、更新、删除等)
connector.async_execute('UPDATE table SET lastsysdate = "20250101"')
# 执行查询操作
select_results = connector.async_execute('SELECT * FROM 表名')
for result in select_results:
print(result)
- 上一篇: python GUI编程:Canvas组件
- 下一篇: 在Python中使用PostgreSQL数据库
猜你喜欢
- 2024-12-16 sqlserver 测试
- 2024-12-16 Python 读写Sqlserver数据库
- 2024-12-16 Python如何解析SQL语句并转换为Python对象,SQLParse类库的使用
- 2024-12-16 Star 4.7k!纯Python开发!自称目前最快的纯Python SQL解析器!
- 2024-12-16 Python 学习 第17篇:sqlalchemy读写SQL
- 2024-12-16 盘点一个通过python大批量插入数据到数据库的方法
- 2024-12-16 python如何操作SQL Server数据库?
- 2024-12-16 Mysql四:常用查询语句(十种),一般情况够用了
- 2024-12-16 在Python中使用PostgreSQL数据库
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 90℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)