<p>我能重现你的问题。MySQL Connector/Python显然不喜欢这样,如果您检索多行,并且在关闭光标或使用它检索某些其他内容之前没有全部获取这些行。例如</p>
<pre class="lang-python prettyprint-override"><code>import mysql.connector
cnxn = mysql.connector.connect(
host='127.0.0.1',
user='root',
password='whatever',
database='mydb')
crsr = cnxn.cursor()
crsr.execute("DROP TABLE IF EXISTS pytest")
crsr.execute("""
CREATE TABLE pytest (
id INT(11) NOT NULL AUTO_INCREMENT,
firstname VARCHAR(20),
PRIMARY KEY (id)
)
""")
crsr.execute("INSERT INTO pytest (firstname) VALUES ('Gord')")
crsr.execute("INSERT INTO pytest (firstname) VALUES ('Anne')")
cnxn.commit()
crsr.execute("SELECT firstname FROM pytest")
fname = crsr.fetchone()[0]
print(fname)
crsr.execute("SELECT firstname FROM pytest") # InternalError: Unread result found.
</code></pre>
<p>如果您只希望(或关心)一行,那么您可以在查询上放置<code>LIMIT</code></p>
<pre class="lang-python prettyprint-override"><code>crsr.execute("SELECT firstname FROM pytest LIMIT 0, 1")
fname = crsr.fetchone()[0]
print(fname)
crsr.execute("SELECT firstname FROM pytest") # OK now
</code></pre>
<p>或者在处理完检索到的行之后,可以使用<code>fetchall()</code>来清除任何未读的结果。</p>
<pre class="lang-python prettyprint-override"><code>crsr.execute("SELECT firstname FROM pytest")
fname = crsr.fetchone()[0]
print(fname)
try:
crsr.fetchall() # fetch (and discard) remaining rows
except mysql.connector.errors.InterfaceError as ie:
if ie.msg == 'No result set to fetch from.':
# no problem, we were just at the end of the result set
pass
else:
raise
crsr.execute("SELECT firstname FROM pytest") # OK now
</code></pre>