尝试使用关闭的游标:"ProgrammingError"

Attempt to use a closed cursor: "ProgrammingError"

我正在尝试将 .csv 文件的内容插入到 SQL 服务器数据库中。

这是我的代码:

cursor = cnxn.cursor()
cursor.execute("Truncate table HumanResources.DepartmentTest") # Truncate old table contents

# Insert Dataframe into SQL Server:
    
    for index, row in df.iterrows():
        cursor.execute("INSERT INTO HumanResources.DepartmentTest (DepartmentID,Name,GroupName) values(?,?,?)", row.DepartmentID, row.Name, row.GroupName)
        cnxn.commit()
        cursor.close()

我在我的 lambda 函数中 运行 以上代码。不确定为什么会出现此错误;

"errorMessage": "Attempt to use a closed cursor."
"errorType": "ProgrammingError"

"stackTrace":
" File "/var/task/lambda_function.py", line 56, in lambda_handler\n cursor.execute("INSERT INTO HumanResources.DepartmentTest (DepartmentID,Name,GroupName) values(?,?,?)", row.DepartmentID, row.Name, row.GroupName)

谁能帮我解决这个问题?

您的 cursor.close() 应该在 for 循环之外:

    for index, row in df.iterrows():
        cursor.execute("INSERT INTO HumanResources.DepartmentTest (DepartmentID,Name,GroupName) values(?,?,?)", row.DepartmentID, row.Name, row.GroupName)
        cnxn.commit()
    cursor.close()