Environment variables¶
This notebook reads its settings from environment variables. Set them before starting Jupyter:
MYSQL_HOST: hostname of your MySQL serverMYSQL_PORT: optional, defaults to3306MYSQL_USER: MySQL user nameMYSQL_PASSWORD: password for that user
Example 1¶
Read data asynchronously from a mysql database
In [ ]:
Copied!
from asyncmy import connect
from asyncmy.cursors import DictCursor
import asyncio
import os
userpwd = os.environ["MYSQL_PASSWORD"]
async def run():
conn = await connect(
host=os.environ["MYSQL_HOST"],
user=os.environ["MYSQL_USER"],
password=userpwd,
port=int(os.environ.get("MYSQL_PORT", "3306")),
)
async with conn.cursor(DictCursor) as cur:
print("Connected")
await cur.execute("create database if not exists test_db")
await cur.execute("""use test_db""")
await cur.execute(
"""CREATE TABLE if not exists another_test_table (
`id` int primary key auto_increment,
`first` varchar(100),
`last` varchar(200)
)
"""
)
await cur.execute("INSERT INTO another_test_table (first, last) VALUES (%s, %s)", ("test_first", "test_lat"))
res = await cur.execute("SELECT * FROM another_test_table;")
print(cur.fetchone())
if __name__ == '__main__':
asyncio.run(run())
from asyncmy import connect
from asyncmy.cursors import DictCursor
import asyncio
import os
userpwd = os.environ["MYSQL_PASSWORD"]
async def run():
conn = await connect(
host=os.environ["MYSQL_HOST"],
user=os.environ["MYSQL_USER"],
password=userpwd,
port=int(os.environ.get("MYSQL_PORT", "3306")),
)
async with conn.cursor(DictCursor) as cur:
print("Connected")
await cur.execute("create database if not exists test_db")
await cur.execute("""use test_db""")
await cur.execute(
"""CREATE TABLE if not exists another_test_table (
`id` int primary key auto_increment,
`first` varchar(100),
`last` varchar(200)
)
"""
)
await cur.execute("INSERT INTO another_test_table (first, last) VALUES (%s, %s)", ("test_first", "test_lat"))
res = await cur.execute("SELECT * FROM another_test_table;")
print(cur.fetchone())
if __name__ == '__main__':
asyncio.run(run())