Query database
Tags: #mysql #database
Author: Unknown

Input

Import libraries

1
import os
2
import pymysql
3
import pandas as pd
Copied!

Variables

1
host = os.getenv('MYSQL_HOST')
2
port = os.getenv('MYSQL_PORT')
3
user = os.getenv('MYSQL_USER')
4
password = os.getenv('MYSQL_PASSWORD')
5
database = os.getenv('MYSQL_DATABASE')
Copied!

Model

Connect to database

1
conn = pymysql.connect(
2
host=host,
3
port=int(port),
4
user=user,
5
passwd=password,
6
db=database,
7
charset='utf8mb4')
Copied!

Send the query

1
df = pd.read_sql_query(
2
"SELECT DATE(created_at) AS date, COUNT(*) AS count FROM user GROUP BY date HAVING date >= '2017-04-01' ",
3
conn)
4
df.tail(10)
Copied!

Output

Display result

1
%matplotlib inline
2
3
df.index = df['date']
4
p = df.tail(10).plot.bar()
Copied!
1
conn.close()
Copied!
Last modified 2mo ago
Copy link
Edit on GitHub