改进当前的SQL脚本以缩短CSV的插入时间

时间:2019-04-21 15:14:43

标签: python mysql csv

我有一个CSV文件,其初始行数不到200000行。

我每天要导入文件,但是读取每一行并插入它们会花费很长时间。

是否有可能改进下面的代码以加快插入速度-我什至每天只需要重新加载完整的csv文件就很高兴!

connection = pymysql.connect(host='', user='', password='', db='', cursorclass=pymysql.cursors.DictCursor, charset='utf8')

csv_data = csv.reader(open('memydataciuri.csv'))
next(csv_data, None)
for row in csv_data:
    date1 = datetime.strptime(row[1],"%Y-%m-%d").date()
    with connection.cursor() as cursor:
        cursor.execute("delete from footballtest where thedatefield =  '"+date1.strftime("%y/%m/%d")+"'")
    date2 = datetime.now().date() - timedelta(90)
    date3 = datetime.now().date() + timedelta(1)
    if date1 >= date2:
        if date1 <= date3:
            print(row[1])
            with connection.cursor() as cursor:

                cursor.execute("INSERT INTO footballtest(`code` ,`thedatefield`,`timeokkickoff` ,`season` ,`round` ,`hometeam`,`awayteam` ,`scor1` ,`scor2` ,`scorp1` ,`scorp2` ,`code1` ,`code2` ,`cotaa` ,`cotae`,`cotad`,`cotao` ,`cotau` ,`suth` ,`suta` ,`sutht`,`sutat` ,`corh` ,`cora` ,`foulsh` ,`foulsa` ,`yellowh`,`yellowa` ,`ballph`,`ballpa` ,`mgolh` ,`mgola` ,`mgol`) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10],row[13],row[14],round(row[16],2),round(row[17],2),round(row[18],2),round(row[19],2),row[20],row[29],row[30],row[31],row[32],row[33],row[34],row[35],row[36],row[37],row[38],row[39],row[40],row[57],row[58],row[59]))

0 个答案:

没有答案