MySQL在Python中;连接在第一个循环后在for循环中关闭 [英] MySQL in Python; connection closes in for loop after first cycle

查看:542
本文介绍了MySQL在Python中;连接在第一个循环后在for循环中关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MySQL连接在一个循环周期后关闭。我可能在使用mysql对象时做错了。

My MySQL connection closes after one loop cycle. I probably do something wrong in the usage of the mysql object. It outputs one cycle and then exits with an error.

这是我的代码:

cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()

fetch_ids = cnx.cursor()
query = ("SELECT * FROM items WHERE has_recipe = 1")
fetch_ids.execute(query)

count = 0
for (data) in fetch_ids:
    fetch_details = cnx.cursor()
    query = ("SELECT * FROM recipes WHERE recipe_id = " + str(data[1]))
    fetch_details.execute(query)

我得到的错误是:

Traceback (most recent call last):
  File "trade.py", line 47, in <module>
    fetch_details = cnx.cursor()
  File "/Users/allendar/Desktop/mysql/connector/connection.py", line 1076, in cursor
    raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.


推荐答案

MySQL不支持真正的游标,只模拟他们。因此,您每次只能在每个连接上运行一个游标。

MySQL doesn't support real cursors, and the library only emulates them. As such, you can only run one cursor per connection at a time.

在循环中打开第二个游标,这不是MySQL可以处理的。在使用游标进行新查询之前,请先读取第一个查询的所有列。

In the loop you are opening a second cursor, and that's not something MySQL can handle. Read all rows from the first query before using the cursor for a new query.

这篇关于MySQL在Python中;连接在第一个循环后在for循环中关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆