Mazahir Bhagat
Mazahir Bhagat

Reputation: 137

Exporting pandas dataframe to MySQL using SQLAlchemy

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

Upvotes: 2

Views: 6608

Answers (2)

Milton
Milton

Reputation: 968

Here is another option:

import pandas as pd
import sqlalchemy

# Read your CSV file into a Pandas dataframe
df = pd.read_csv("test.csv")

# Store the dataframe in MySQL
engine = sqlalchemy.create_engine('mysql+mysqlconnector://user:[email protected]/schema')

with engine.begin() as connection:
    df.to_sql('your_table', con=connection, if_exists='replace', index=False)

Upvotes: 0

Mazahir Bhagat
Mazahir Bhagat

Reputation: 137

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

Upvotes: 2

Related Questions