我有一个DataFrame,它有大约30,000+行和150+列。因此,当前我正在使用以下代码将数据插入MySQL。但是由于它一次读取一行,所以将所有行插入MySql花费了太多时间。
有什么方法可以一次或批量插入所有行?这里的约束是我只需要使用PyMySQL,就不能安装任何其他库。
import pymysql
import pandas as pd
# Create dataframe
data = pd.DataFrame({
'book_id':[12345, 12346, 12347],
'title':['Python Programming', 'Learn MySQL', 'Data Science Cookbook'],
'price':[29, 23, 27]
})
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='12345',
db='book')
# create cursor
cursor=connection.cursor()
# creating column list for insertion
cols = "`,`".join([str(i) for i in data.columns.tolist()])
# Insert DataFrame recrds one by one.
for i,row in data.iterrows():
sql = "INSERT INTO `book_details` (`" +cols + "`) VALUES (" + "%s,"*(len(row)-1) + "%s)"
cursor.execute(sql, tuple(row))
# the connection is not autocommitted by default, so we must commit to save our changes
connection.commit()
# Execute query
sql = "SELECT * FROM `book_details`"
cursor.execute(sql)
# Fetch all the records
result = cursor.fetchall()
for i in result:
print(i)
connection.close()
谢谢。
答案 0 :(得分:1)
可能的改进。
现在尝试加载数据。
生成CSV文件并使用** LOAD DATA INFILE **加载-这将从mysql内部发出。
答案 1 :(得分:1)
尝试使用SQLALCHEMY创建引擎,然后再将其与pandas df.to_sql函数一起使用。此函数将熊猫数据帧中的行写入SQL数据库,这比迭代DataFrame和使用MySql游标要快得多。
您的代码应如下所示:
import pymysql
import pandas as pd
from sqlalchemy import create_engine
# Create dataframe
data = pd.DataFrame({
'book_id':[12345, 12346, 12347],
'title':['Python Programming', 'Learn MySQL', 'Data Science Cookbook'],
'price':[29, 23, 27]
})
db_data = 'mysql+mysqldb://' + 'root' + ':' + '12345' + '@' + 'localhost' + ':3306/' \
+ 'book' + '?charset=utf8mb4'
engine = create_engine(db_data)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='12345',
db='book')
# create cursor
cursor=connection.cursor()
# Execute the to_sql for writting DF into SQL
data.to_sql('book_details', engine, if_exists='append', index=False)
# Execute query
sql = "SELECT * FROM `book_details`"
cursor.execute(sql)
# Fetch all the records
result = cursor.fetchall()
for i in result:
print(i)
engine.dispose()
connection.close()
您可以查看此功能在pandas doc
中具有的所有选项答案 2 :(得分:1)
将文件推送到SQL服务器并让服务器管理输入更快。
因此,首先将数据推送到CSV文件。
data.to_csv("import-data.csv", header=False, index=False, quoting=2, na_rep="\\N")
然后立即将其加载到SQL表中。
sql = "LOAD DATA LOCAL INFILE \'import-data.csv\' \
INTO TABLE book_details FIELDS TERMINATED BY \',\' ENCLOSED BY \'\"\' \
(`" +cols + "`)"
cursor.execute(sql)