gzc*_*gzc 5 python mysql mysql-connector-python
我想从游标中读取部分结果,然后在不读取所有结果的情况下关闭它。cursor.close()raisesInternalError: Unread result found.是否可以在不遍历所有结果或使用缓冲区选项的情况下关闭游标?
更新:
我的查询获得大约 3000 条记录,我的目标是获得符合某些条件的前几条记录。在迭代部分结果后,我得到了我想要的。然后我想放弃未读的结果。我不使用缓冲区选项,据我所知,它会立即读取所有结果。这个问题不是Python MySQL 连接器的重复- 使用 fetchone 时发现未读结果
def chooseInstrumentsFromOrigin(self, time):
sql = """select symbol, name, total_ratio, outstanding_ratio from market_values
where time = %s order by {captype} asc""".format(captype=self.strategy_data['captype'])
args = [time]
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor(dictionary=True)
cursor.execute(sql, args)
# This function will return half way.
symbols = self.chooseInstrumentsFromLeaders(time, cursor)
# I don't want this line!
for i in cursor: pass
cursor.close()
conn.close()
return symbols
Run Code Online (Sandbox Code Playgroud)
看起来你需要:
cursor = conn.cursor(buffered=True,dictionary=true)
Run Code Online (Sandbox Code Playgroud)
为了在中途放弃结果集。
完全公开,我是 mysql 开发人员,而不是 python 开发人员。
请参阅 Python 手册页MySQLConnection.cursor() 方法和cursor.MySQLCursorBuffered 类。
立即读取所有行,为真。非常适合中小型结果集。
上面的后一个参考说明:
对于使用缓冲游标执行的查询,诸如 fetchone() 之类的行提取方法会从缓冲行集中返回行。对于非缓冲游标,在调用行提取方法之前不会从服务器提取行。在这种情况下,您必须确保在同一连接上执行任何其他语句之前获取结果集的所有行,否则将引发 InternalError (Unread result found) 异常。
作为旁注,您可以使用分页来修改您的策略。MySQLLIMIT clause通过 offset,pageSize 设置支持这一点:
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
Run Code Online (Sandbox Code Playgroud)