Created
October 16, 2015 21:08
-
-
Save msure/24ce45067d598fa7a5b6 to your computer and use it in GitHub Desktop.
Alternative MySQL Querying
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import mysql.connector | |
import numpy as np | |
import pandas as pd | |
from pandas import Series, DataFrame | |
# p as path, c as connection | |
with open('/Users/path/to/database/keys/prod_db.json') as p: | |
c = json.load(p) | |
p.close() | |
query_users = """ | |
SELECT users.id,users.attributes | |
FROM users | |
WHERE users.created_at > '2013-12-31 23:59:59' | |
""" | |
# accepts query and list of column names, returns dataframe | |
def get_mysql_data(q,cols): | |
cnx = mysql.connector.connect(user=c['user'],password=c['password'],host=c['host'],database=c['dbname']) | |
cursor = cnx.cursor() | |
cursor.execute(q) | |
data = cursor.fetchall() | |
df = pd.DataFrame(data,columns=cols) | |
cursor.close() | |
cnx.close() | |
return df | |
users = get_mysql_data(query_users,['user_id','attributes']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@msure I saw a link to this on Stack Overflow, and just out of interest: is this faster than using the pandas
read_sql_query
and sqlalchemy?As I would not expect it to be (and you gave the link on a question about speed)