我使用aimysql。我用异步方式访问mysql。所以我使用aimysql。但运行时间(当aimysql不使用时)与aimysql使用的运行时间相同。
from sqlalchemy import create_engine
import pymysql
pymysql.install_as_MySQLdb()
import pandas as pd
engine = create_engine("mysql+mysqldb://root:"+"qhdks12#$"+"@localhost/stock", encoding='utf-8')
conn = pymysql.connect(host='localhost', user='root', password="qhdks12#$", db='stock', charset='utf8')
cursor = conn.cursor()
def test():
for i in range(10):
sql = "select * from test;"
data = pd.read_sql(sql, conn, index_col=None)
%timeit test()
以上代码,aimysql不使用。在jupyter笔记本中,test()函数的运行时间是“3.1s”± 39.3毫秒
import asyncio
import aiomysql as aiomysql
import pandas as pd
async def main(loop):
pool = await aiomysql.create_pool(host='127.0.0.1', port=3306, user='root', password='qhdks12#$', db='stock', loop=loop)
for i in range(2):
await test(pool, loop)
async def test(pool, loop):
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("select * from test;")
rows = ()
rows = await cur.fetchall()
result = pd.DataFrame.from_records(list(rows))
loop = asyncio.get_event_loop()
%timeit loop.run_until_complete(main(loop))
以上代码,aimysql使用。在jupyter笔记本中,主(循环)功能运行时间为“3.05秒± 每回路107 ms”
运行时间相同。我认为上面的代码不能将db与asynchronous连接起来。
所以,我通常不知道。如何用异步连接db???
1条答案
按热度按时间vatpfxk51#
以下代码是同步的。如果你大声读出来,你就是在循环,等待每个测试完成后再继续。
要异步发送请求,可以使用wait或gather等待所有请求。