Exporting pandas dataframe to MySQL using SQLAlchemy

淺唱寂寞╮ 提交于 2019-12-11 04:47:45

问题


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)

Following is the error:

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


回答1:


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

Code:

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


来源:https://stackoverflow.com/questions/48689682/exporting-pandas-dataframe-to-mysql-using-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!