批量导入文本文件(如 .txt
文件)到 MySQL 数据库是一种常见的数据迁移或数据初始化操作。它通常涉及将大量数据从一个格式(如 CSV 或 TSV)转换为数据库表中的记录。
LOAD DATA INFILE
)而不是逐条插入。iconv
)转换文件编码。以下是一个使用 Python 和 mysql-connector-python
库批量导入 CSV 文件到 MySQL 数据库的示例代码:
import mysql.connector
import csv
# 连接到 MySQL 数据库
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = db.cursor()
# 打开 CSV 文件
with open('data.csv', newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
next(reader) # 跳过标题行
for row in reader:
# 构造插入语句
sql = "INSERT INTO yourtable (column1, column2, column3) VALUES (%s, %s, %s)"
cursor.execute(sql, row)
# 提交事务并关闭连接
db.commit()
cursor.close()
db.close()
注意:在实际应用中,请确保替换示例代码中的占位符(如 yourusername
、yourpassword
、yourdatabase
、yourtable
、column1
等)为实际的值。
领取专属 10元无门槛券
手把手带您无忧上云