加入聊天记录入库动作

This commit is contained in:
liuwei
2025-02-06 11:47:04 +08:00
parent 3354782204
commit c8b59eb788
3 changed files with 67 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
CREATE DATABASE message_archive charset utf8mb4;
USE message_archive;
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
timestamp VARCHAR(20) NOT NULL,
sender VARCHAR(255) NOT NULL,
content TEXT NULL,
message_type VARCHAR(50) NULL,
attachment_url VARCHAR(512) DEFAULT NULL
);

View File

@@ -0,0 +1,46 @@
import pymysql
# 配置数据库连接
db_config = {
'host': '192.168.2.32', # 替换为你的MariaDB服务器地址
'user': 'root', # 替换为你的MariaDB用户名
'password': 'lw123456', # 替换为你的MariaDB密码
'database': 'message_archive'
}
def archive_message(timestamp_str, sender, content, message_type, attachment_url=None):
# 连接到数据库
connection = pymysql.connect(**db_config)
try:
with connection.cursor() as cursor:
# 插入消息信息
sql = """
INSERT INTO messages (timestamp, sender, content, message_type, attachment_url)
VALUES (%s, %s, %s, %s, %s)
"""
cursor.execute(sql, (timestamp_str, sender, content, message_type, attachment_url))
# 提交事务
connection.commit()
print("Message archived successfully.")
except Exception as e:
print(f"Error archiving message: {e}")
connection.rollback()
finally:
# 关闭连接
connection.close()
# 示例用法
if __name__ == "__main__":
timestamp_str = "2025-02-06 11:15:28"
sender = "XXX"
content = "This is a test message with a string timestamp."
message_type = "text"
attachment_url = "http://example.com/attachment.pdf" # 可以为None如果没有附件
archive_message(timestamp_str, sender, content, message_type, attachment_url)