Skip to content

Instantly share code, notes, and snippets.

@sebastien-collet
Created October 20, 2016 10:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastien-collet/1a5596c3055c794a09e40991dc113710 to your computer and use it in GitHub Desktop.
Save sebastien-collet/1a5596c3055c794a09e40991dc113710 to your computer and use it in GitHub Desktop.
import pandas as pd
import mysql.connector
from sqlalchemy import create_engine
# ====== Connection ======
# Connecting to mysql by providing a sqlachemy engine
engine = create_engine('mysql+mysqlconnector://os.environ['MYSQL_USER']:os.environ['MYSQL_PASSWORD']@os.environ['MYSQL_HOST_IP']:os.environ['MYSQL_PORT']/sandbox', echo=False)
# ====== Writing table ======
# Creating a simple pandas DataFrame with two columns
liste_hello = ['hello1','hello2']
liste_world = ['world1','world2']
df = pd.DataFrame(data = {'hello' : liste_hello, 'world': liste_world})
# Writing Dataframe to mysql and replacing table if it already exists
df.to_sql(name='helloworld', con=engine, if_exists = 'replace', index=False)
# ====== Reading table ======
# Reading Mysql table into a pandas DataFrame
data = pd.read_sql('SELECT * FROM helloworld', engine)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment