使用SQLAlchemy将 pandas 数据框导出到MySQL [英] Exporting pandas dataframe to MySQL using SQLAlchemy

查看:125
本文介绍了使用SQLAlchemy将 pandas 数据框导出到MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算使用SQLAlchemy将熊猫数据框导出到MySQL.尽管提到了以前的所有文章,但我仍无法解决该问题:

I intend to export a pandas dataframe to MySQL using SQLAlchemy. Despite referring to all previous posts, I am unable to solve the issue:

import pandas as pd
import pymysql
from sqlalchemy import create_engine

df=pd.read_excel(r"C:\Users\mazin\1-601.xlsx")

cnx = create_engine('mysql+pymysql://[root]:[aUtO1115]@[localhost]:[3306]/[patenting in psis]', echo=False)

df.to_sql(name='inventor_dataset', con=cnx, if_exists = 'replace', index=False)

以下是错误:

OperationalError:(pymysql.err.OperationalError)(2003,无法连接 到本地主机"上的MySQL服务器上:[3306]([Errno 11001] getaddrinfo 失败)")

OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost]:[3306' ([Errno 11001] getaddrinfo failed)")

推荐答案

在对代码进行了大量修改并探索了Python中的不同程序包之后,我得以使代码正常工作.

After a lot of tinkering with the code and exploring different packages in Python, I was able to make the code work.

代码:

import mysql.connector
import sqlalchemy

database_username = 'root'
database_password = 'mysql'
database_ip       = '127.0.0.1'
database_name     = 'patenting_in_psi'
database_connection = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'.
                                               format(database_username, database_password, 
                                                      database_ip, database_name), pool_recycle=1, pool_timeout=57600).connect()

df22.to_sql(con=database_connection, name='university_dataset_ca', if_exists='append',chunksize=100)
database_connection.close()

这篇关于使用SQLAlchemy将 pandas 数据框导出到MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆