You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

126 lines
3.5 KiB
Python

import sqlite3
import os
import datetime
# 定义数据库文件的名称
DATABASE_FILENAME = "database.db"
# 获取当前文件 (database.py) 的绝对路径
current_file_path = os.path.abspath(__file__)
# 获取当前文件所在的目录
current_dir_path = os.path.dirname(current_file_path)
# 获取项目根目录 (假设 database.py 在某个子目录中)
project_root = os.path.dirname(current_dir_path)
# 构建 assets 目录的路径
assets_dir = os.path.join(project_root, "assets")
# 构建数据库文件的完整路径
DB_PATH = os.path.join(assets_dir, DATABASE_FILENAME)
def init_db():
"""
初始化 SQLite 数据库和 messages 表。
如果表已存在,则不会重复创建。
"""
if not os.path.exists(assets_dir):
os.makedirs(assets_dir)
db_exists = os.path.exists(DB_PATH)
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS messages (
id TEXT ,
file_id TEXT,
update_time TEXT,
sent INTEGER,
file_path TEXT,
contact_name TEXT
)
""")
conn.commit()
conn.close()
if not db_exists:
print(f"数据库文件 '{DB_PATH}' 已创建并初始化。")
else:
print(f"数据库文件 '{DB_PATH}' 已存在,跳过创建。")
def get_latest_update_time():
"""
查询 messages 表中最大的 update_time。
如果没有数据,则返回当前的系统时间。
返回格式: 'YYYY-MM-DD HH:MM:SS'
"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# 查询最大的 update_time
cursor.execute("SELECT MAX(update_time) FROM messages")
result = cursor.fetchone()[0]
conn.close()
if result:
return result
else:
# 如果没有数据,返回当前时间
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def insert_many_messages(messages_to_insert):
"""
批量插入数据到 messages 表。
messages_to_insert 是一个包含 (id, update_time, sent) 元组的列表。
例如: [('id1', '2023-10-27 10:00:00', 0), ('id2', '2023-10-27 10:05:00', 0)]
"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# 使用 executemany 进行批量插入,性能更好
cursor.executemany("INSERT OR IGNORE INTO messages VALUES (?, ?, ?,?,?,?)", messages_to_insert)
conn.commit()
conn.close()
except Exception as e:
return e
print(f"已批量插入 {len(messages_to_insert)} 条数据到数据库。")
return None
def update_sent_status(id,contact_name,sent):
"""
根据给定的 ID 列表,将 sent 字段更新为 1 (已发送)。
ids_to_update 是一个包含 ID 的列表或元组。
例如: ['id1', 'id2', 'id3']
"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# 构建 SQL 语句,使用 IN 子句批量更新
sql_query = "UPDATE messages SET sent = ? WHERE id = ? and contact_name = ?"
cursor.execute(sql_query, (sent, id,contact_name))
conn.commit()
conn.close()
print(f"已更新 {cursor.rowcount} 条数据的 sent 状态。")
def query_by_sent(sent):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# 查询所有匹配给定 ID 的记录
cursor.execute("SELECT id, file_id, update_time, sent,file_path,contact_name FROM messages WHERE sent = ?", (sent,))
results = cursor.fetchall()
conn.close()
# 返回查询结果列表
return results