Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python MySQL执行查询循环,光标关闭_Python_Mysql Python - Fatal编程技术网

Python MySQL执行查询循环,光标关闭

Python MySQL执行查询循环,光标关闭,python,mysql-python,Python,Mysql Python,这是复制的样本: import mysql.connector conn = mysql.connector.connect( user='root', password='12347', host='localhost') def getCursor(): return conn.cursor() def execQuery(cursor=getCursor()): cursor.execute("SELECT 2") cursor.fetchall() cur

这是复制的样本:

import mysql.connector

conn =  mysql.connector.connect(
  user='root', password='12347',
  host='localhost')

def getCursor():
  return conn.cursor()

def execQuery(cursor=getCursor()):
  cursor.execute("SELECT 2")
  cursor.fetchall()
  cursor.close()

for i in range(4):
  cursor = execQuery()
此代码在没有光标的情况下工作。关闭()。但我觉得奇怪的是,这个示例甚至可以与cursor.close()配合使用,只是做了一个简单的更改:

def execQuery():
  cursor=getCursor()
  cursor.execute("SELECT 2")
  cursor.fetchall()
  cursor.close()
通过将默认参数移动到函数体

我不知道关闭光标是否是最好的做法,因此我可以在保留第一个表单时跳过关闭光标。如果使用使用函数返回值的默认参数不是最佳做法,我可以使用第二种形式但我想知道为什么他们的行为不同

这就像我犯了与以下相同的错误:

cursor.execute("SELECT 2")
cursor.fetchall()
cursor.close()
cursor.execute("SELECT 2")

就像每次调用execQuery都使用同一个游标,所以它在第二次调用时就被阻止了。

当您需要连接到数据库时,您需要类似游标的东西。您需要一个游标对象来获取结果

在示例程序中,在范围(4)中运行循环时,它调用
execQuery()
。查看定义,您可以找到
def execQuery(cursor=getCursor()):
该函数将输入作为游标,默认情况下使用
getCursor()
函数,该函数在执行循环时创建游标所有内容


在您的程序中,您正在关闭光标,但没有再次创建光标,因此当第二次执行查询出现时,没有光标,程序将抛出错误。

谢谢您的回答。我认为“在……时创建游标的函数”应该是“每次游标”,不是吗?不管怎样,从您的回答中我了解到,每次在循环中调用
execQuery
,它都会创建游标。然后你说我关闭光标,不再创建它。您是说当第二次执行
execQuery
时,游标没有创建,因为它已关闭?你能告诉我为什么它没有被再次创建吗?