Debian Codegraph @

examples/example_transaction_oldstyle.py

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