mysql-api 0.1.0__tar.gz
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.
mysql_api-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: mysql-api
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 封装mysql操作
|
|
5
|
+
Author: LiuWei
|
|
6
|
+
Author-email: 183074632@qq.com
|
|
7
|
+
Requires-Python: >=3.8
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Requires-Dist: pymysql (>=1.1.1,<2.0.0)
|
|
16
|
+
Requires-Dist: sqlalchemy (>=2.0.36,<3.0.0)
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
### Mysql 数据库封装
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
### Mysql 数据库封装
|
|
File without changes
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""mysql_api exception module."""
|
|
2
|
+
|
|
3
|
+
class MySQLAPIError(Exception):
|
|
4
|
+
"""Base class for mysql_api exceptions."""
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MySQLAPIConnectionError(MySQLAPIError):
|
|
8
|
+
"""Exception raised when there is a connection error."""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MySQLAPIQueryError(MySQLAPIError):
|
|
12
|
+
"""Exception raised when there is a query error."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MySQLAPIAddError(MySQLAPIError):
|
|
16
|
+
"""Exception raised when there is an add error."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MySQLAPIUploadError(MySQLAPIError):
|
|
20
|
+
"""Exception raised when there is an upload error."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MySQLAPIDeleteError(MySQLAPIError):
|
|
24
|
+
"""Exception raised when there is a delete error."""
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Mysql 数据库模块."""
|
|
2
|
+
import logging
|
|
3
|
+
from typing import Union, Dict
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import create_engine, text
|
|
6
|
+
from sqlalchemy.exc import DatabaseError
|
|
7
|
+
from sqlalchemy.orm import sessionmaker, scoped_session
|
|
8
|
+
from sqlalchemy.orm.decl_api import DeclarativeMeta
|
|
9
|
+
|
|
10
|
+
from mysql_api.exception import MySQLAPIAddError, MySQLAPIQueryError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# pylint: disable=R0913, R0917
|
|
14
|
+
# noinspection SqlNoDataSourceInspection
|
|
15
|
+
class MySQLDatabase:
|
|
16
|
+
"""MySQLDatabase class."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, user_name, password, database_name: str = "cyg", host: str = "127.0.0.1", port: int = 3306):
|
|
19
|
+
self.logger = logging.getLogger(__name__)
|
|
20
|
+
self.engine = create_engine(
|
|
21
|
+
f"mysql+pymysql://{user_name}:{password}@{host}:{port}/{database_name}?charset=utf8mb4", echo=True
|
|
22
|
+
)
|
|
23
|
+
self.session = scoped_session(sessionmaker(bind=self.engine))
|
|
24
|
+
|
|
25
|
+
@staticmethod
|
|
26
|
+
def create_database(user_name: str, password: str, db_name: str, host: str = "127.0.0.1", port: int = 3306):
|
|
27
|
+
"""创建数据库.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
user_name: 用户名.
|
|
31
|
+
password: 密码.
|
|
32
|
+
host: 数据库服务地址ip.
|
|
33
|
+
port:端口号.
|
|
34
|
+
db_name: 要创建的数据库名称.
|
|
35
|
+
"""
|
|
36
|
+
engine = create_engine(f"mysql+pymysql://{user_name}:{password}@{host}:{port}", echo=True)
|
|
37
|
+
with engine.connect() as con:
|
|
38
|
+
con.execute(text(f"CREATE DATABASE IF NOT EXISTS {db_name}"))
|
|
39
|
+
|
|
40
|
+
def create_table(self, declarative_base: DeclarativeMeta):
|
|
41
|
+
"""在执行数据库下创建数据表.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
declarative_base: SQLAlchemy的declarative_base对象.
|
|
45
|
+
"""
|
|
46
|
+
declarative_base.metadata.create_all(self.engine)
|
|
47
|
+
|
|
48
|
+
def add_data(self, model_cls, data: dict):
|
|
49
|
+
"""向指定数据表添加一行数据.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
model_cls: 数据表模型class.
|
|
53
|
+
data: 要添加的数据, 键值对形式.
|
|
54
|
+
|
|
55
|
+
Raises:
|
|
56
|
+
MySQLAPIAddError: 添加数据失败抛出异常.
|
|
57
|
+
"""
|
|
58
|
+
with self.session() as session:
|
|
59
|
+
try:
|
|
60
|
+
new_instance = model_cls(**data)
|
|
61
|
+
session.add(new_instance)
|
|
62
|
+
session.commit()
|
|
63
|
+
except DatabaseError as e:
|
|
64
|
+
session.rollback()
|
|
65
|
+
raise MySQLAPIAddError(f"Failed to add data to {model_cls.__name__}: {e}") from e
|
|
66
|
+
|
|
67
|
+
def update_data(
|
|
68
|
+
self, model_cls, key: str, key_value: Union[str, int, float],
|
|
69
|
+
update_values: Dict[str, Union[str, int, float]]
|
|
70
|
+
):
|
|
71
|
+
"""向指定数据表更新数据.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
model_cls: 数据表模型class.
|
|
75
|
+
key: 要更新的字段名.
|
|
76
|
+
key_value: key字段的值.
|
|
77
|
+
update_values: 要更新的字段值.
|
|
78
|
+
|
|
79
|
+
Raises:
|
|
80
|
+
MySQLAPIAddError: 更新数据失败抛出异常.
|
|
81
|
+
"""
|
|
82
|
+
with self.session() as session:
|
|
83
|
+
try:
|
|
84
|
+
if instances := self.query_data(model_cls, **{key: key_value}):
|
|
85
|
+
for instance in instances:
|
|
86
|
+
for field, value in update_values.items():
|
|
87
|
+
setattr(instance, field, value)
|
|
88
|
+
session.commit()
|
|
89
|
+
except DatabaseError as e:
|
|
90
|
+
session.rollback()
|
|
91
|
+
raise MySQLAPIAddError(f"Failed to add data to {model_cls.__name__}: {e}") from e
|
|
92
|
+
|
|
93
|
+
def query_data(self, model_cls, **filters: Dict[str, Union[int, str, float]]):
|
|
94
|
+
"""查询指定模型的数据.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
model_cls: SQLAlchemy 模型类.
|
|
98
|
+
filters: 查询条件,以关键字参数传入.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
list: 查询结果列表.
|
|
102
|
+
|
|
103
|
+
Raises:
|
|
104
|
+
MySQLAPIQueryError: 查询失败抛出异常.
|
|
105
|
+
"""
|
|
106
|
+
with self.session() as session:
|
|
107
|
+
try:
|
|
108
|
+
return session.query(model_cls).filter_by(**filters).all()
|
|
109
|
+
except DatabaseError as e:
|
|
110
|
+
raise MySQLAPIQueryError(f"Failed to query data for {model_cls.__name__}: {e}") from e
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "mysql-api"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "封装mysql操作"
|
|
5
|
+
authors = ["LiuWei <183074632@qq.com>"]
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
|
|
8
|
+
[tool.poetry.dependencies]
|
|
9
|
+
python = ">=3.8"
|
|
10
|
+
sqlalchemy = "^2.0.36"
|
|
11
|
+
pymysql = "^1.1.1"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
[build-system]
|
|
15
|
+
requires = ["poetry-core"]
|
|
16
|
+
build-backend = "poetry.core.masonry.api"
|