dc-cmnutils 0.0.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dc/cmnutils/basicdata/convert.py +192 -0
- dc/cmnutils/basicdata/convert_basic.py +393 -0
- dc/cmnutils/basicdata/data.py +588 -0
- dc/cmnutils/basicdata/json.py +94 -0
- dc/cmnutils/basicdata/object.py +814 -0
- dc/cmnutils/collection/collection.py +757 -0
- dc/cmnutils/database/database_access.py +213 -0
- dc/cmnutils/database/database_accessor.py +287 -0
- dc/cmnutils/database/db_operater.py +283 -0
- dc/cmnutils/database/dbutil.py +389 -0
- dc/cmnutils/io/file/cfg/config.py +262 -0
- dc/cmnutils/io/file/file.py +212 -0
- dc/cmnutils/io/file/file_utils.py +605 -0
- dc/cmnutils/io/log/log.py +43 -0
- dc/cmnutils/io/log/log_utils.py +50 -0
- dc/cmnutils/net/email.py +185 -0
- dc/cmnutils/net/http.py +468 -0
- dc/cmnutils/net/net.py +252 -0
- dc/cmnutils/sys/env/linuxenv.py +384 -0
- dc/cmnutils/sys/env/windowsenv.py +235 -0
- dc/cmnutils/sys/envutil.py +442 -0
- dc/cmnutils/sys/processutil.py +447 -0
- dc/cmnutils/sys/sys.py +640 -0
- dc/cmnutils/sys/sys_utils.py +580 -0
- dc/cmnutils/sys/threadutil.py +315 -0
- dc_cmnutils-0.0.3.dist-info/METADATA +34 -0
- dc_cmnutils-0.0.3.dist-info/RECORD +30 -0
- dc_cmnutils-0.0.3.dist-info/WHEEL +5 -0
- dc_cmnutils-0.0.3.dist-info/licenses/LICENSE.TXT +19 -0
- dc_cmnutils-0.0.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
通用数据库访问类
|
|
4
|
+
支持任何符合 DB-API 2.0 (PEP 249) 的数据库连接对象。
|
|
5
|
+
提供 execute、select、insert、update、delete 等标准操作。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
import logging
|
|
10
|
+
from typing import Any, Dict, List, Optional, Sequence, Union, Tuple
|
|
11
|
+
|
|
12
|
+
# 配置日志记录器(可替换为自己的日志系统)
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
logger.addHandler(logging.NullHandler())
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class DatabaseAccess:
|
|
18
|
+
"""
|
|
19
|
+
通用数据库访问类,封装常见的 SQL 操作。
|
|
20
|
+
|
|
21
|
+
Attributes:
|
|
22
|
+
connection: 数据库连接对象(需符合 DB-API 2.0)
|
|
23
|
+
auto_commit: 是否自动提交事务(默认 False)
|
|
24
|
+
_cursor: 当前使用的游标(内部使用)
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, connection: Any, auto_commit: bool = False) -> None:
|
|
28
|
+
"""
|
|
29
|
+
初始化数据库访问对象。
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
connection: 数据库连接对象,必须支持 commit()、rollback()、cursor() 等方法。
|
|
33
|
+
auto_commit: 若为 True,每次执行更新操作后自动提交事务。
|
|
34
|
+
"""
|
|
35
|
+
self.connection = connection
|
|
36
|
+
self.auto_commit = auto_commit
|
|
37
|
+
self._cursor = None
|
|
38
|
+
|
|
39
|
+
def __enter__(self) -> "DatabaseAccess":
|
|
40
|
+
"""上下文管理器入口,返回自身。"""
|
|
41
|
+
return self
|
|
42
|
+
|
|
43
|
+
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
44
|
+
"""
|
|
45
|
+
上下文管理器出口。
|
|
46
|
+
若无异常则提交事务,否则回滚,并确保游标和连接被关闭。
|
|
47
|
+
"""
|
|
48
|
+
if exc_type is None:
|
|
49
|
+
self.commit()
|
|
50
|
+
else:
|
|
51
|
+
self.rollback()
|
|
52
|
+
logger.error(f"事务回滚,异常: {exc_val}")
|
|
53
|
+
self.close()
|
|
54
|
+
|
|
55
|
+
def _get_cursor(self) -> Any:
|
|
56
|
+
"""
|
|
57
|
+
获取游标对象,若不存在则创建。
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
游标对象。
|
|
61
|
+
"""
|
|
62
|
+
if self._cursor is None:
|
|
63
|
+
self._cursor = self.connection.cursor()
|
|
64
|
+
return self._cursor
|
|
65
|
+
|
|
66
|
+
def execute(self, sql: str, params: Optional[Union[Sequence, Dict]] = None) -> Any:
|
|
67
|
+
"""
|
|
68
|
+
执行任意 SQL 语句(支持参数化查询)。
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
sql: SQL 语句,可使用占位符(如 %s 或 :name,取决于驱动)。
|
|
72
|
+
params: 参数序列或字典,用于替换占位符。
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
游标对象,便于进一步处理结果。
|
|
76
|
+
|
|
77
|
+
Raises:
|
|
78
|
+
Exception: 执行失败时抛出异常(由上层处理)。
|
|
79
|
+
"""
|
|
80
|
+
cursor = self._get_cursor()
|
|
81
|
+
try:
|
|
82
|
+
logger.debug(f"执行 SQL: {sql}, 参数: {params}")
|
|
83
|
+
if params is None:
|
|
84
|
+
cursor.execute(sql)
|
|
85
|
+
else:
|
|
86
|
+
cursor.execute(sql, params)
|
|
87
|
+
# 若设置了自动提交且是更新操作(非查询),则提交
|
|
88
|
+
if self.auto_commit and sql.strip().upper().startswith(('INSERT', 'UPDATE', 'DELETE')):
|
|
89
|
+
self.commit()
|
|
90
|
+
return cursor
|
|
91
|
+
except Exception as e:
|
|
92
|
+
logger.error(f"SQL 执行失败: {e}")
|
|
93
|
+
raise
|
|
94
|
+
|
|
95
|
+
def select(self, sql: str, params: Optional[Union[Sequence, Dict]] = None,
|
|
96
|
+
as_dict: bool = False) -> List[Union[Tuple, Dict]]:
|
|
97
|
+
"""
|
|
98
|
+
执行查询语句,返回所有结果行。
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
sql: SELECT 语句。
|
|
102
|
+
params: 参数。
|
|
103
|
+
as_dict: 若为 True,每行以字典形式返回(列名 -> 值);否则返回元组。
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
列表,包含所有结果行。
|
|
107
|
+
|
|
108
|
+
Raises:
|
|
109
|
+
Exception: 查询失败时抛出。
|
|
110
|
+
"""
|
|
111
|
+
cursor = self.execute(sql, params)
|
|
112
|
+
if as_dict:
|
|
113
|
+
# 获取列名
|
|
114
|
+
columns = [desc[0] for desc in cursor.description] if cursor.description else []
|
|
115
|
+
rows = cursor.fetchall()
|
|
116
|
+
return [dict(zip(columns, row)) for row in rows]
|
|
117
|
+
else:
|
|
118
|
+
return cursor.fetchall()
|
|
119
|
+
|
|
120
|
+
def select_one(self, sql: str, params: Optional[Union[Sequence, Dict]] = None,
|
|
121
|
+
as_dict: bool = False) -> Optional[Union[Tuple, Dict]]:
|
|
122
|
+
"""
|
|
123
|
+
执行查询,返回第一行结果。
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
sql: SELECT 语句。
|
|
127
|
+
params: 参数。
|
|
128
|
+
as_dict: 若为 True,返回字典;否则返回元组。
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
第一行结果,若没有结果则返回 None。
|
|
132
|
+
"""
|
|
133
|
+
rows = self.select(sql, params, as_dict)
|
|
134
|
+
return rows[0] if rows else None
|
|
135
|
+
|
|
136
|
+
def insert(self, sql: str, params: Optional[Union[Sequence, Dict]] = None) -> int:
|
|
137
|
+
"""
|
|
138
|
+
执行 INSERT 语句,返回插入行的主键(若支持)或影响行数。
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
sql: INSERT 语句。
|
|
142
|
+
params: 参数。
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
若游标支持 lastrowid 则返回该值,否则返回影响行数(rowcount)。
|
|
146
|
+
"""
|
|
147
|
+
cursor = self.execute(sql, params)
|
|
148
|
+
# 尝试获取最后插入的行 ID(适用于 SQLite、MySQL、PostgreSQL 等)
|
|
149
|
+
if hasattr(cursor, 'lastrowid') and cursor.lastrowid is not None:
|
|
150
|
+
return cursor.lastrowid
|
|
151
|
+
else:
|
|
152
|
+
return cursor.rowcount
|
|
153
|
+
|
|
154
|
+
def update(self, sql: str, params: Optional[Union[Sequence, Dict]] = None) -> int:
|
|
155
|
+
"""
|
|
156
|
+
执行 UPDATE 语句,返回影响行数。
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
sql: UPDATE 语句。
|
|
160
|
+
params: 参数。
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
影响的行数 (cursor.rowcount)。
|
|
164
|
+
"""
|
|
165
|
+
cursor = self.execute(sql, params)
|
|
166
|
+
return cursor.rowcount
|
|
167
|
+
|
|
168
|
+
def delete(self, sql: str, params: Optional[Union[Sequence, Dict]] = None) -> int:
|
|
169
|
+
"""
|
|
170
|
+
执行 DELETE 语句,返回影响行数。
|
|
171
|
+
|
|
172
|
+
Args:
|
|
173
|
+
sql: DELETE 语句。
|
|
174
|
+
params: 参数。
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
影响的行数 (cursor.rowcount)。
|
|
178
|
+
"""
|
|
179
|
+
cursor = self.execute(sql, params)
|
|
180
|
+
return cursor.rowcount
|
|
181
|
+
|
|
182
|
+
def commit(self) -> None:
|
|
183
|
+
"""提交当前事务。"""
|
|
184
|
+
self.connection.commit()
|
|
185
|
+
logger.debug("事务已提交")
|
|
186
|
+
|
|
187
|
+
def rollback(self) -> None:
|
|
188
|
+
"""回滚当前事务。"""
|
|
189
|
+
self.connection.rollback()
|
|
190
|
+
logger.debug("事务已回滚")
|
|
191
|
+
|
|
192
|
+
def close(self) -> None:
|
|
193
|
+
"""关闭游标和连接(连接不会自动关闭,由调用者管理)。"""
|
|
194
|
+
if self._cursor:
|
|
195
|
+
self._cursor.close()
|
|
196
|
+
self._cursor = None
|
|
197
|
+
# 注意:不主动关闭 connection,因为连接可能由外部管理
|
|
198
|
+
logger.debug("游标已关闭")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# 额外提供的便捷函数(可选)
|
|
202
|
+
def create_database_access(connection: Any, auto_commit: bool = False) -> DatabaseAccess:
|
|
203
|
+
"""
|
|
204
|
+
工厂函数,创建数据库访问对象。
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
connection: 数据库连接对象。
|
|
208
|
+
auto_commit: 自动提交标志。
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
DatabaseAccess 实例。
|
|
212
|
+
"""
|
|
213
|
+
return DatabaseAccess(connection, auto_commit)
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""
|
|
2
|
+
通用数据库访问类模块。
|
|
3
|
+
|
|
4
|
+
本模块提供了一个与数据库无关的访问层,遵循 PEP 249 (Python Database API Specification)。
|
|
5
|
+
只需传入符合 DB-API 2.0 规范的连接对象即可操作各种数据库。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from typing import Any, List, Dict, Optional, Union
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
|
|
12
|
+
# 配置日志
|
|
13
|
+
logging.basicConfig(level=logging.INFO)
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class DatabaseAccessor:
|
|
18
|
+
"""
|
|
19
|
+
通用数据库访问类,支持所有符合 DB-API 2.0 规范的数据库。
|
|
20
|
+
|
|
21
|
+
使用示例:
|
|
22
|
+
import sqlite3
|
|
23
|
+
conn = sqlite3.connect(':memory:')
|
|
24
|
+
db = DatabaseAccessor(conn)
|
|
25
|
+
result = db.select("SELECT * FROM users")
|
|
26
|
+
|
|
27
|
+
Attributes:
|
|
28
|
+
connection: 数据库连接对象,必须实现 DB-API 2.0 规范
|
|
29
|
+
#cursor: 数据库游标对象
|
|
30
|
+
_in_transaction: 是否处于事务中
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, connection: Any) -> None:
|
|
34
|
+
"""
|
|
35
|
+
初始化数据库访问器。
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
connection: 数据库连接对象,必须实现以下方法:
|
|
39
|
+
- cursor(): 返回游标对象
|
|
40
|
+
- commit(): 提交事务
|
|
41
|
+
- rollback(): 回滚事务
|
|
42
|
+
- close(): 关闭连接
|
|
43
|
+
|
|
44
|
+
Raises:
|
|
45
|
+
ValueError: 当连接对象无效时抛出
|
|
46
|
+
"""
|
|
47
|
+
if not hasattr(connection, 'cursor'):
|
|
48
|
+
raise ValueError("连接对象必须实现 cursor() 方法")
|
|
49
|
+
|
|
50
|
+
self.connection = connection
|
|
51
|
+
self._in_transaction = False
|
|
52
|
+
logger.info(f"数据库访问器已初始化,连接对象: {type(connection).__name__}")
|
|
53
|
+
|
|
54
|
+
@contextmanager
|
|
55
|
+
def transaction(self) -> 'DatabaseAccessor':
|
|
56
|
+
"""
|
|
57
|
+
事务上下文管理器,用于确保原子性操作。
|
|
58
|
+
|
|
59
|
+
Yields:
|
|
60
|
+
DatabaseAccessor: 当前实例
|
|
61
|
+
|
|
62
|
+
Example:
|
|
63
|
+
with db.transaction() as tx:
|
|
64
|
+
tx.insert(...)
|
|
65
|
+
tx.update(...)
|
|
66
|
+
# 自动提交或回滚
|
|
67
|
+
"""
|
|
68
|
+
try:
|
|
69
|
+
self._in_transaction = True
|
|
70
|
+
yield self
|
|
71
|
+
self.connection.commit()
|
|
72
|
+
logger.debug("事务已提交")
|
|
73
|
+
except Exception as e:
|
|
74
|
+
self.connection.rollback()
|
|
75
|
+
logger.error(f"事务回滚: {e}")
|
|
76
|
+
raise
|
|
77
|
+
finally:
|
|
78
|
+
self._in_transaction = False
|
|
79
|
+
|
|
80
|
+
def select(
|
|
81
|
+
self,
|
|
82
|
+
sql: str,
|
|
83
|
+
params: Optional[Union[List, Dict]] = None,
|
|
84
|
+
fetch_all: bool = True
|
|
85
|
+
) -> List[tuple]:
|
|
86
|
+
"""
|
|
87
|
+
执行 SELECT 查询。
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
sql: SQL 查询语句,可使用参数占位符(? 或 %s 等)
|
|
91
|
+
params: 查询参数,可以是列表或字典
|
|
92
|
+
fetch_all: 是否获取所有结果,False 则只获取第一条
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
List[tuple]: 查询结果集,每行是一个元组
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
RuntimeError: 当查询执行失败时抛出
|
|
99
|
+
"""
|
|
100
|
+
try:
|
|
101
|
+
with self.connection.cursor() as cursor:
|
|
102
|
+
cursor.execute(sql, params or [])
|
|
103
|
+
|
|
104
|
+
if fetch_all:
|
|
105
|
+
result = cursor.fetchall()
|
|
106
|
+
else:
|
|
107
|
+
result = [cursor.fetchone()] if cursor.rowcount > 0 else []
|
|
108
|
+
|
|
109
|
+
logger.debug(f"SELECT 执行成功,影响行数: {len(result)}")
|
|
110
|
+
return result
|
|
111
|
+
|
|
112
|
+
except Exception as e:
|
|
113
|
+
logger.error(f"SELECT 执行失败: {e}\nSQL: {sql}\nParams: {params}")
|
|
114
|
+
raise RuntimeError(f"查询执行失败: {e}")
|
|
115
|
+
|
|
116
|
+
def insert(
|
|
117
|
+
self,
|
|
118
|
+
sql: str,
|
|
119
|
+
params: Optional[Union[List, Dict]] = None,
|
|
120
|
+
return_last_id: bool = False
|
|
121
|
+
) -> Union[int, None]:
|
|
122
|
+
"""
|
|
123
|
+
执行 INSERT 语句。
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
sql: INSERT SQL 语句
|
|
127
|
+
params: 插入参数
|
|
128
|
+
return_last_id: 是否返回最后插入的 ID(需要数据库支持)
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
Union[int, None]: 最后插入的 ID(如果支持),否则返回受影响的行数
|
|
132
|
+
|
|
133
|
+
Raises:
|
|
134
|
+
RuntimeError: 当插入失败时抛出
|
|
135
|
+
"""
|
|
136
|
+
try:
|
|
137
|
+
with self.connection.cursor() as cursor:
|
|
138
|
+
cursor.execute(sql, params or [])
|
|
139
|
+
|
|
140
|
+
# 尝试获取最后插入的 ID
|
|
141
|
+
last_id = None
|
|
142
|
+
if return_last_id:
|
|
143
|
+
try:
|
|
144
|
+
# 不同数据库获取方式不同,这里尝试常见方式
|
|
145
|
+
last_id = cursor.lastrowid
|
|
146
|
+
except AttributeError:
|
|
147
|
+
# 如果不支持 lastrowid,尝试其他方法
|
|
148
|
+
pass
|
|
149
|
+
|
|
150
|
+
if not self._in_transaction:
|
|
151
|
+
self.connection.commit()
|
|
152
|
+
|
|
153
|
+
affected_rows = cursor.rowcount
|
|
154
|
+
logger.debug(f"INSERT 执行成功,影响行数: {affected_rows}")
|
|
155
|
+
|
|
156
|
+
return last_id if return_last_id else affected_rows
|
|
157
|
+
|
|
158
|
+
except Exception as e:
|
|
159
|
+
logger.error(f"INSERT 执行失败: {e}\nSQL: {sql}\nParams: {params}")
|
|
160
|
+
raise RuntimeError(f"插入执行失败: {e}")
|
|
161
|
+
|
|
162
|
+
def update(
|
|
163
|
+
self,
|
|
164
|
+
sql: str,
|
|
165
|
+
params: Optional[Union[List, Dict]] = None
|
|
166
|
+
) -> int:
|
|
167
|
+
"""
|
|
168
|
+
执行 UPDATE 语句。
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
sql: UPDATE SQL 语句
|
|
172
|
+
params: 更新参数
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
int: 受影响的行数
|
|
176
|
+
|
|
177
|
+
Raises:
|
|
178
|
+
RuntimeError: 当更新失败时抛出
|
|
179
|
+
"""
|
|
180
|
+
try:
|
|
181
|
+
with self.connection.cursor() as cursor:
|
|
182
|
+
cursor.execute(sql, params or [])
|
|
183
|
+
|
|
184
|
+
if not self._in_transaction:
|
|
185
|
+
self.connection.commit()
|
|
186
|
+
|
|
187
|
+
affected_rows = cursor.rowcount
|
|
188
|
+
logger.debug(f"UPDATE 执行成功,影响行数: {affected_rows}")
|
|
189
|
+
return affected_rows
|
|
190
|
+
|
|
191
|
+
except Exception as e:
|
|
192
|
+
logger.error(f"UPDATE 执行失败: {e}\nSQL: {sql}\nParams: {params}")
|
|
193
|
+
raise RuntimeError(f"更新执行失败: {e}")
|
|
194
|
+
|
|
195
|
+
def delete(
|
|
196
|
+
self,
|
|
197
|
+
sql: str,
|
|
198
|
+
params: Optional[Union[List, Dict]] = None
|
|
199
|
+
) -> int:
|
|
200
|
+
"""
|
|
201
|
+
执行 DELETE 语句。
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
sql: DELETE SQL 语句
|
|
205
|
+
params: 删除参数
|
|
206
|
+
|
|
207
|
+
Returns:
|
|
208
|
+
int: 受影响的行数
|
|
209
|
+
|
|
210
|
+
Raises:
|
|
211
|
+
RuntimeError: 当删除失败时抛出
|
|
212
|
+
"""
|
|
213
|
+
try:
|
|
214
|
+
with self.connection.cursor() as cursor:
|
|
215
|
+
cursor.execute(sql, params or [])
|
|
216
|
+
|
|
217
|
+
if not self._in_transaction:
|
|
218
|
+
self.connection.commit()
|
|
219
|
+
|
|
220
|
+
affected_rows = cursor.rowcount
|
|
221
|
+
logger.debug(f"DELETE 执行成功,影响行数: {affected_rows}")
|
|
222
|
+
return affected_rows
|
|
223
|
+
|
|
224
|
+
except Exception as e:
|
|
225
|
+
logger.error(f"DELETE 执行失败: {e}\nSQL: {sql}\nParams: {params}")
|
|
226
|
+
raise RuntimeError(f"删除执行失败: {e}")
|
|
227
|
+
|
|
228
|
+
def execute_many(
|
|
229
|
+
self,
|
|
230
|
+
sql: str,
|
|
231
|
+
params_list: List[Union[List, Dict]]
|
|
232
|
+
) -> int:
|
|
233
|
+
"""
|
|
234
|
+
批量执行 SQL 语句(如批量插入)。
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
sql: SQL 语句
|
|
238
|
+
params_list: 参数列表
|
|
239
|
+
|
|
240
|
+
Returns:
|
|
241
|
+
int: 总受影响的行数
|
|
242
|
+
"""
|
|
243
|
+
try:
|
|
244
|
+
with self.connection.cursor() as cursor:
|
|
245
|
+
cursor.executemany(sql, params_list)
|
|
246
|
+
|
|
247
|
+
if not self._in_transaction:
|
|
248
|
+
self.connection.commit()
|
|
249
|
+
|
|
250
|
+
total_affected = cursor.rowcount
|
|
251
|
+
logger.debug(f"批量执行完成,总影响行数: {total_affected}")
|
|
252
|
+
return total_affected
|
|
253
|
+
|
|
254
|
+
except Exception as e:
|
|
255
|
+
logger.error(f"批量执行失败: {e}\nSQL: {sql}")
|
|
256
|
+
raise RuntimeError(f"批量执行失败: {e}")
|
|
257
|
+
|
|
258
|
+
def close(self) -> None:
|
|
259
|
+
"""关闭数据库连接。"""
|
|
260
|
+
try:
|
|
261
|
+
self.connection.close()
|
|
262
|
+
logger.info("数据库连接已关闭")
|
|
263
|
+
except Exception as e:
|
|
264
|
+
logger.warning(f"关闭连接时出现警告: {e}")
|
|
265
|
+
|
|
266
|
+
def __enter__(self) -> 'DatabaseAccessor':
|
|
267
|
+
"""上下文管理器入口。"""
|
|
268
|
+
return self
|
|
269
|
+
|
|
270
|
+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
271
|
+
"""上下文管理器出口,自动关闭连接。"""
|
|
272
|
+
self.close()
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
# 辅助函数:验证连接对象是否符合 DB-API 规范
|
|
276
|
+
def validate_connection(connection: Any) -> bool:
|
|
277
|
+
"""
|
|
278
|
+
验证连接对象是否符合 DB-API 2.0 规范。
|
|
279
|
+
|
|
280
|
+
Args:
|
|
281
|
+
connection: 要验证的连接对象
|
|
282
|
+
|
|
283
|
+
Returns:
|
|
284
|
+
bool: 是否符合规范
|
|
285
|
+
"""
|
|
286
|
+
required_methods = ['cursor', 'commit', 'rollback', 'close']
|
|
287
|
+
return all(hasattr(connection, method) for method in required_methods)
|