Skip to content

Instantly share code, notes, and snippets.

@nisrulz
Last active December 29, 2016 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nisrulz/049c4d76b758e14e177c381858c4219c to your computer and use it in GitHub Desktop.
Save nisrulz/049c4d76b758e14e177c381858c4219c to your computer and use it in GitHub Desktop.
MySQL connection in python
import MySQLdb
import pandas as pd
from sqlalchemy import create_engine
# read the csv into pandas and then export to MySQL
template_lines = 1000
df = pd.read_csv(
'example.csv', nrows=template_lines, low_memory=False)
# 2nd argument replaces where conditions is False
df = df.where(pd.notnull(df), None)
df.head()
# <user>:<password>@<host>[:<port>]/<dbname>
conn_str = "mysql+mysqldb://root:qwerty@127.0.0.1/testdb?charset=utf8&use_unicode=0"
engine = create_engine(conn_str)
conn = engine.connect()
df.to_sql("data", con=conn)
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment