python - 向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()
''''
解决方案
我认为最好的方法是将数据传递到 DataFrame 中,然后使用 .to_sql 方法将数据保存在 MySQL 数据库中。此方法采用一个参数(method='multi'),它允许您在很短的时间内一次性将所有数据插入 DataFrame 中。如果您的数据库允许多写入,则此方法有效。在这里阅读更多:https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
推荐阅读
- angular - 更新失败:TypeError:无法读取未定义的属性“注入器”
- javascript - 如何修复 angular.min.js:108 TypeError: Cannot read property 'length' of undefined error is shown Angular js pagination
- bash - 在bash中捕获一个psql(PostgreSQL)命令错误,可以通用,与sql无关
- php - 在foreach中使用递归函数替换PHP数组值
- python - Python:从字符串中删除选定的空格
- vuejs2 - vue-i18n - 检测“未知”类型的令牌
- reactjs - 如何设置 aws-sdk 以从 s3 存储桶中的公共文件中获取文件内容?
- javascript - 动态加载图像,图像错误时中断循环
- wordpress - WP 重定向功能在实时站点上不起作用
- performance - Liferay 7 中搜索容器的性能不佳