python - mysql 批量导出数据库表超大数据
场景:MySQL 导出大表数据到 TXT 文件
问题:
1.超大数据量引起诸多不便, 比如数据库显示不全, 导出数据不能用文本直接打开
2.导出数据
import mysql.connector
config = {
'user':'xxxxxxxx',
'password':'xxxxxxxx',
'host':'xx.xx.xx.xx',
'port':xxxx,
'database':'xxxxxx',
'raise_on_warnings':True
}
#分批处理参数
batch_size = 100000
offset = 0
with open('output.txt', 'w') as f:
while True:
#连接数据库
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
#查询语句
query = f"SELECT column_name FROM table_name LIMIT {batch_size} OFFSET {offset}"
cursor.execute(query)
#获取当前结果
rows = cursor.fetchall()
if not rows:
break
# 写入文件
for row in rows:
f.write(str(row) + '\n')
#关闭连接
cursor.close()
cnx.close()
#更新偏移量
offset += batch_size
print(f"已处理 {offset} 条数据")
优点:可以把控操作内容 \ 进度

浙公网安备 33010602011771号