| 1 |
import asyncio |
| 2 |
import aiomysql |
| 3 |
|
| 4 |
|
| 5 |
async def test_example_executemany(loop): |
| 6 |
conn = await aiomysql.connect(host='127.0.0.1', port=3306, |
| 7 |
user='root', password='', |
| 8 |
db='test_pymysql', loop=loop) |
| 9 |
|
| 10 |
cur = await conn.cursor() |
| 11 |
async with conn.cursor() as cur: |
| 12 |
await cur.execute("DROP TABLE IF EXISTS music_style;") |
| 13 |
await cur.execute("""CREATE TABLE music_style |
| 14 |
(id INT, |
| 15 |
name VARCHAR(255), |
| 16 |
PRIMARY KEY (id));""") |
| 17 |
await conn.commit() |
| 18 |
|
| 19 |
# insert 3 rows one by one |
| 20 |
await cur.execute("INSERT INTO music_style VALUES(1,'heavy metal')") |
| 21 |
await cur.execute("INSERT INTO music_style VALUES(2,'death metal');") |
| 22 |
await cur.execute("INSERT INTO music_style VALUES(3,'power metal');") |
| 23 |
await conn.commit() |
| 24 |
|
| 25 |
# insert 3 row by one long query using *executemany* method |
| 26 |
data = [(4, 'gothic metal'), (5, 'doom metal'), (6, 'post metal')] |
| 27 |
await cur.executemany( |
| 28 |
"INSERT INTO music_style (id, name)" |
| 29 |
"values (%s,%s)", data) |
| 30 |
await conn.commit() |
| 31 |
|
| 32 |
# fetch all insert row from table music_style |
| 33 |
await cur.execute("SELECT * FROM music_style;") |
| 34 |
result = await cur.fetchall() |
| 35 |
print(result) |
| 36 |
|
| 37 |
conn.close() |
| 38 |
|
| 39 |
|
| 40 |
loop = asyncio.get_event_loop() |
| 41 |
loop.run_until_complete(test_example_executemany(loop)) |