import os import pymysql db_config = { 'host': '192.168.100.188', 'user': 'root', 'password': 'Csiq@2019', 'db': 'porn', 'charset': 'utf8mb4', 'cursorclass': pymysql.cursors.DictCursor } # 连接到数据库 directory_path = 'C:\\games\\H\\h-corpus' # 遍历指定目录下的所有.txt文件 for filename in os.listdir(directory_path): if filename.endswith('.txt'): file_path = os.path.join(directory_path, filename) try: # 打开数据库连接 connection = pymysql.connect(max_allowed_packet=1024 * 1024 * 64, **db_config) with connection.cursor() as cursor: with open(file_path, 'r', encoding='utf-8') as file: title = file.readline().strip() # 读取标题 content = file.read().strip() # 读取内容 # 插入数据到数据库 sql = "INSERT INTO hnote (title, content) VALUES (%s, %s)" cursor.execute(sql, (title, content)) # 提交事务 connection.commit() except Exception as e: print(f"An error occurred: {e}") finally: # 关闭数据库连接 if connection: connection.close() print("All .txt files have been processed and inserted into the database.")