File size: 1,360 Bytes
4925137 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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.") |