简体   繁体   English

cursor.execute返回1个整数

[英]cursor.execute returns 1 int

When running a query to a mysql database using MySqlHook, cursor.execute(query) returns int 1 My code is 使用MySqlHook对mysql数据库运行查询时,cursor.execute(query)返回int 1我的代码是

import logging
from airflow.hooks.mysql_hook import MySqlHook
query = "SELECT col1, col2 FROM myschema.mytable LIMIT 1"
mysql = MySqlHook(mysql_conn_id=conn_id)
conn = mysql.get_conn()
cursor = conn.cursor()
result_cursor = cursor.execute(query)
logging.info(result_cursor) # this prints out "INFO - 1" in the log
df = pd.DataFrame(result_cursor.fetchall(), columns=result_cursor.keys()) # this triggers error "ERROR - 'int' object has no attribute 'fetchall'"

I would have expected result_cursor to return a "fetchable" result, since the query is working fine. 我希望期望result_cursor返回“可获取”的结果,因为查询工作正常。

Cursor.execute() return value is not defined by the db-api spec , but for most implementations it returns the number of rows affected by the query. db-api规范未定义Cursor.execute()返回值,但对于大多数实现,它返回受查询影响的行数。

To retrieve data, you have to either iterate over the cursor or call .fetchall() . 要检索数据,您必须遍历光标或调用.fetchall()

It seems I cannot save cursor.execute(query) into variable result_cursor. 看来我无法将cursor.execute(query)保存到变量result_cursor中。 To make the code work, I simply needed to define the data for the data-frame as cursor.fetchall() 为了使代码正常工作,我只需要将数据帧的数据定义为cursor.fetchall()

cursor.execute(query)
df = pd.DataFrame(list(cursor.fetchall()), column=[col[0] for col in cursor.description])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM