为什么Python MySQL插入表不起作用



我正在使用aiomysqlMariaDB。我可以创建表或选择数据,但不能将数据插入表中。如果您使用fetchall()SELECT数据,那么它将显示您刚刚插入的内容,但会立即从数据库中删除。

async def test_example(loop):
pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
user='root', password='',
db='test', loop=loop)
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("INSERT INTO `tbl`(`id`, `val`) VALUES (37, 'z');")
print(cur.fetchall())
pool.close()
await pool.wait_closed()
loop = asyncio.get_event_loop()
loop.run_until_complete(test_example(loop))

为什么?

来自PEP-249规范:

.fetchall((

获取查询结果的所有(剩余(行,将它们作为序列(例如元组列表(返回

由于sqlINSERT语句不会生成结果集,因此在尝试从数据库服务器获取信息之前,应该先尝试SELECT语句。

删除表和列名中的引号。

import aiomysql
import asyncio

async def select(loop, sql, pool):
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
r = await cur.fetchone()
print(r)

async def insert(loop, sql, pool):
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
await conn.commit()

async def main(loop):
pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
user='root', password='',
db='test', loop=loop)
c1 = select(loop=loop, sql='select * from tbl', pool=pool)
c2 = insert(loop=loop, sql="INSERT INTO tbl(id, val) VALUES (37, 'z');", pool=pool)
tasks = [asyncio.ensure_future(c1), asyncio.ensure_future(c2)]
return await asyncio.gather(*tasks)

if __name__ == '__main__':
cur_loop = asyncio.get_event_loop()
cur_loop.run_until_complete(main(cur_loop))

最新更新