簡體   English   中英

如何使用 PyMySQL 將 Pandas Dataframe 插入 MySql

[英]How to insert a Pandas Dataframe into MySql using PyMySQL

我有一個 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()

謝謝你。

可能的改進。

  • 刪除或禁用表上的索引
  • 將提交移出循環

現在嘗試加載數據。

生成 CSV 文件並使用 ** LOAD DATA INFILE ** 加載 - 這將從 mysql 中發出。

嘗試使用 SQLALCHEMY 創建引擎,而不是稍后與 pandas df.to_sql function 一起使用。 This function writes rows from pandas dataframe to SQL database and it is much faster than iterating your DataFrame and using the MySql cursor.

您的代碼將如下所示:

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()

您可以查看 function 在pandas 文檔中的所有選項

將文件推送到 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM