43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
import pymysql
|
|
|
|
# MySQL 配置
|
|
db_config = {
|
|
'host': '192.168.2.32',
|
|
'user': 'root',
|
|
'password': 'lw123456',
|
|
'database': 'message_archive'
|
|
}
|
|
|
|
|
|
# 获取消息列表,按时间倒序
|
|
def get_messages(page=1, per_page=10):
|
|
try:
|
|
connection = pymysql.connect(**db_config)
|
|
with connection.cursor() as cursor:
|
|
offset = (page - 1) * per_page
|
|
cursor.execute(
|
|
"SELECT id, group_id, timestamp, sender, content FROM messages ORDER BY timestamp DESC LIMIT %s OFFSET %s",
|
|
(per_page, offset))
|
|
messages = cursor.fetchall()
|
|
return messages
|
|
except pymysql.MySQLError as e:
|
|
print(f"数据库查询失败: {e}")
|
|
return []
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
# 获取消息总数
|
|
def get_total_messages():
|
|
try:
|
|
connection = pymysql.connect(**db_config)
|
|
with connection.cursor() as cursor:
|
|
cursor.execute("SELECT COUNT(*) FROM messages")
|
|
total = cursor.fetchone()[0]
|
|
return total
|
|
except pymysql.MySQLError as e:
|
|
print(f"数据库查询失败: {e}")
|
|
return 0
|
|
finally:
|
|
connection.close()
|