1+ # 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
2+ # 1. 不得用于任何商业用途。
3+ # 2. 使用时应遵守目标平台的使用条款和robots.txt规则。
4+ # 3. 不得进行大规模爬取或对平台造成运营干扰。
5+ # 4. 应合理控制请求频率,避免给目标平台带来不必要的负担。
6+ # 5. 不得用于任何非法或不当的用途。
7+ #
8+ # 详细许可条款请参阅项目根目录下的LICENSE文件。
9+ # 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
10+
11+
12+ # -*- coding: utf-8 -*-
13+ # @Author : relakkes@gmail.com
14+ # @Time : 2024/4/6 14:21
15+ # @Desc : 异步SQLite的增删改查封装
16+ from typing import Any , Dict , List , Union
17+
18+ import aiosqlite
19+
20+
21+ class AsyncSqliteDB :
22+ def __init__ (self , db_path : str ) -> None :
23+ self .__db_path = db_path
24+
25+ async def query (self , sql : str , * args : Union [str , int ]) -> List [Dict [str , Any ]]:
26+ """
27+ 从给定的 SQL 中查询记录,返回的是一个列表
28+ :param sql: 查询的sql
29+ :param args: sql中传递动态参数列表
30+ :return:
31+ """
32+ async with aiosqlite .connect (self .__db_path ) as conn :
33+ conn .row_factory = aiosqlite .Row
34+ async with conn .execute (sql , args ) as cursor :
35+ rows = await cursor .fetchall ()
36+ return [dict (row ) for row in rows ] if rows else []
37+
38+ async def get_first (self , sql : str , * args : Union [str , int ]) -> Union [Dict [str , Any ], None ]:
39+ """
40+ 从给定的 SQL 中查询记录,返回的是符合条件的第一个结果
41+ :param sql: 查询的sql
42+ :param args:sql中传递动态参数列表
43+ :return:
44+ """
45+ async with aiosqlite .connect (self .__db_path ) as conn :
46+ conn .row_factory = aiosqlite .Row
47+ async with conn .execute (sql , args ) as cursor :
48+ row = await cursor .fetchone ()
49+ return dict (row ) if row else None
50+
51+ async def item_to_table (self , table_name : str , item : Dict [str , Any ]) -> int :
52+ """
53+ 表中插入数据
54+ :param table_name: 表名
55+ :param item: 一条记录的字典信息
56+ :return:
57+ """
58+ fields = list (item .keys ())
59+ values = list (item .values ())
60+ fieldstr = ',' .join (fields )
61+ valstr = ',' .join (['?' ] * len (item ))
62+ sql = f"INSERT INTO { table_name } ({ fieldstr } ) VALUES({ valstr } )"
63+ async with aiosqlite .connect (self .__db_path ) as conn :
64+ async with conn .execute (sql , values ) as cursor :
65+ await conn .commit ()
66+ return cursor .lastrowid
67+
68+ async def update_table (self , table_name : str , updates : Dict [str , Any ], field_where : str ,
69+ value_where : Union [str , int , float ]) -> int :
70+ """
71+ 更新指定表的记录
72+ :param table_name: 表名
73+ :param updates: 需要更新的字段和值的 key - value 映射
74+ :param field_where: update 语句 where 条件中的字段名
75+ :param value_where: update 语句 where 条件中的字段值
76+ :return:
77+ """
78+ upsets = []
79+ values = []
80+ for k , v in updates .items ():
81+ upsets .append (f'{ k } =?' )
82+ values .append (v )
83+ upsets_str = ',' .join (upsets )
84+ values .append (value_where )
85+ sql = f'UPDATE { table_name } SET { upsets_str } WHERE { field_where } =?'
86+ async with aiosqlite .connect (self .__db_path ) as conn :
87+ async with conn .execute (sql , values ) as cursor :
88+ await conn .commit ()
89+ return cursor .rowcount
90+
91+ async def execute (self , sql : str , * args : Union [str , int ]) -> int :
92+ """
93+ 需要更新、写入等操作的 excute 执行语句
94+ :param sql:
95+ :param args:
96+ :return:
97+ """
98+ async with aiosqlite .connect (self .__db_path ) as conn :
99+ async with conn .execute (sql , args ) as cursor :
100+ await conn .commit ()
101+ return cursor .rowcount
102+
103+ async def executescript (self , sql_script : str ) -> None :
104+ """
105+ 执行SQL脚本,用于初始化数据库表结构
106+ :param sql_script: SQL脚本内容
107+ :return:
108+ """
109+ async with aiosqlite .connect (self .__db_path ) as conn :
110+ await conn .executescript (sql_script )
111+ await conn .commit ()
0 commit comments