今天把php上写的搜索功能移植到了python上,自然又遇到了mysql查询返回多个结果的问题。总的来讲,我一直用的pymysql是无法解决这个问题的,我使用了现在mysql官方的python mysql connecter(https://dev.mysql.com/doc/connector-python/en)

https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
文档这里最后给了一个例子,对于多结果查询,需要遍历cursor.execute的返回值

operation = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cursor.execute(operation, multi=True):
if result.with_rows:
print("Rows produced by statement '{}':".format(
result.statement))
print(result.fetchall())
else:
print("Number of rows affected by statement '{}': {}".format(
result.statement, result.rowcount))

with_rows = false时遍历到末尾(末尾为空)
亲测可用

Leave a comment

电子邮件地址不会被公开。 必填项已用*标注