首页 > 解决方案 > 向mysql插入数据?一个一个或一个整体的数据哪一个是更好的方法呢?

问题描述

我是编程初学者,如果问题很愚蠢,请原谅。

请参阅下面的代码。它从名为耳机_master_data.csv(价格,链接)的 csv 文件中获取两个值,并将数据写入 MySQL 表。写入数据时,日期也被写入表中。

文件中有 900 行。看到写部分,my_cursor.execute(sql, val) 函数执行了900次(行数)。

这让我开始思考,我想看看是否有其他方法可以改进数据写入部分。我想出了两个想法,它们如下。

1 - 将所有列表(价格、链接)转换为字典并编写字典。所以 my_cursor.execute(sql, val) 函数只执行一次。

2 - 将列表转换为数据框并将其写入数据库,这样写入只发生一次。

哪种方法最好?只写一次数据有什么缺点吗?更重要的是,我是否正确考虑了优化?

''''

import pandas as pd

import pymysql


data = pd.read_csv("headphones-master_data.csv") #read csv file and save this into a variable named data

link_list = data['Product_url'].tolist()  #taking athe url value from the data vaiable and turn into a list

price_list = data['Sale_price'].tolist()

crawled_date = time.strftime('%Y-%m-%d') #generate the date format compatiable with MySQL

connection = pymysql.connect(host='localhost',
                         user='root',
                         password='passme123@#$',
                         db='hpsize')   #connection obhect to pass the database details


my_cursor = connection.cursor() #curser object to communicate with database


for i in range(len(link_list)):

    link = link_list[i]

    price = price_list[i]



    sql = "INSERT INTO comparison (link, price, crawled_date) VALUES (%s, %s, %s)" #sql query to add data to database with three variables

    val = link , price , crawled_date  #the variables to be addded to the SQL query


    my_cursor.execute(sql, val)  #execute the curser obhect to insert the data

    connection.commit() #commit and make the insert permanent


my_cursor.execute("SELECT * from comparison") #load the table contents to verify the insert

result = my_cursor.fetchall()

for i in result:
    print(i)

connection.close()

''''

标签: pythonmysqldatabasepymysql

解决方案


我认为最好的方法是将数据传递到 DataFrame 中,然后使用 .to_sql 方法将数据保存在 MySQL 数据库中。此方法采用一个参数(method='multi'),它允许您在很短的时间内一次性将所有数据插入 DataFrame 中。如果您的数据库允许多写入,则此方法有效。在这里阅读更多:https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html


推荐阅读