Exporting pandas dataframe to MySQL using SQLAlche

2019-07-29 03:37发布

问题:

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