【发布时间】:2021-02-28 21:55:38
【问题描述】:
我遇到了 80.000 行以上的大文件,我必须将这些文件保存在我的数据库中。将它全部推送到我的 mysql 数据库需要 20-30 分钟。我有一个简单的 for 循环,它只是循环整个 csv。
import csv
import MySQLdb
# open the connection to the MySQL server.
# using MySQLdb
mydb = MySQLdb.connect(host='hst', user='usr', passwd='pwd', db='db')
cursor = mydb.cursor()
with open('product_de.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
# execute and insert the csv into the database.
for row in csv_reader:
if "PVP_BIG" and "DATE_ADD" in row:
print "First line removed"
else:
print "Not found!"
sql = "INSERT INTO big (SKU,Category,Attribute1,Attribute2,Value1,Value2,Brand,Price,PVP_BIG,PVD,EAN13,WIDTH,HEIGHT,DEPTH,WEIGHT,Stock) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
val = (row[0], row[1],row[3],row[4], row[5],row[6], row[8], row[10], row[11], row[12], row[15], row[16], row[17], row[18], row[19], row[20])
cursor.execute(sql, val)
print row
#close the connection to the database.
#mydb.commit()
cursor.close()
print "CSV has been imported into the database"
有什么方法,我可以把它分成并发,所以根据计算机硬件可能需要3-5分钟?
【问题讨论】:
-
可能会有所帮助。试试executemany。
-
你为什么不用
LOAD DATA INFILE ...? -
另请注意,
if "PVP_BIG" and "DATE_ADD" in row:将始终评估为True -
@SuperStew 它不会。我测试了它。如果在一行csv中都找到了,则为True,否则为非
-
好的,那么您可以使用dev.mysql.com/doc/refman/8.0/en/mysqlimport.html 指定
--host=host_name--password[=password]等