问题
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.
This is my code:
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)
The error I get is:
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.
回答1:
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.
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.
回答2:
You're calling cnx.cursor() too many times. Just call the cursor the first time like you're doing and reuse the same object for the following queries. When you are finished dealing with you db, remember to put a cnx.close() somewhere to clean the session.
来源:https://stackoverflow.com/questions/14564359/mysql-in-python-connection-closes-in-for-loop-after-first-cycle