Debian Codegraph @

examples/example_transaction.py

raw
1 import asyncio
2 import aiomysql
3
4
5 async def test_example_transaction(loop):
6 conn = await aiomysql.connect(host='127.0.0.1', port=3306,
7 user='root', password='',
8 db='test_pymysql', autocommit=False,
9 loop=loop)
10
11 async with conn.cursor() as cursor:
12 stmt_drop = "DROP TABLE IF EXISTS names"
13 await cursor.execute(stmt_drop)
14 await cursor.execute("""
15 CREATE TABLE names (
16 id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
17 name VARCHAR(30) DEFAULT '' NOT NULL,
18 cnt TINYINT UNSIGNED DEFAULT 0,
19 PRIMARY KEY (id))""")
20 await conn.commit()
21
22 # Insert 3 records
23 names = (('Geert',), ('Jan',), ('Michel',))
24 stmt_insert = "INSERT INTO names (name) VALUES (%s)"
25 await cursor.executemany(stmt_insert, names)
26
27 # Roll back!!!!
28 await conn.rollback()
29
30 # There should be no data!
31 stmt_select = "SELECT id, name FROM names ORDER BY id"
32 await cursor.execute(stmt_select)
33 resp = await cursor.fetchall()
34 # Check there is no data
35 assert not resp
36
37 # Do the insert again.
38 await cursor.executemany(stmt_insert, names)
39
40 # Data should be already there
41 await cursor.execute(stmt_select)
42 resp = await cursor.fetchall()
43 print(resp)
44 # Do a commit
45 await conn.commit()
46
47 await cursor.execute(stmt_select)
48 print(resp)
49
50 # Cleaning up, dropping the table again
51 await cursor.execute(stmt_drop)
52 await cursor.close()
53 conn.close()
54
55
56 loop = asyncio.get_event_loop()
57 loop.run_until_complete(test_example_transaction(loop))