PYTHONWarningDatabase ErrorApril 24, 2026

Database Error

psycopg2.errors.InvalidCursorName: cursor is closed

What This Error Means

This error occurs when you try to use a cursor object after it has been closed in PostgreSQL using the psycopg2 library. A cursor object is used to execute SQL commands, and once it's closed, it can't be used again.

Why It Happens

This error typically happens when you close a cursor inside a loop or after executing a query, but then try to use it again outside of the loop or after another query has been executed. This can also occur when you have a global cursor object that's being used across multiple functions or classes, and one of those functions or classes accidentally closes it.

How to Fix It

  1. 1To fix this error, you should ensure that you only close the cursor when you're finished using it. If you need to reuse the cursor, you can create a new one. Make sure to close the cursor in a finally block to avoid memory leaks. Here's an example of how to fix this issue:
  2. 2// Before (broken code)
  3. 3conn = psycopg2.connect(database='mydb')
  4. 4cur = conn.cursor()
  5. 5try:
  6. 6 cur.execute('SELECT * FROM mytable')
  7. 7 cur.close() # Close the cursor here
  8. 8 print(cur) # Try to use the closed cursor
  9. 9// After (fixed code)
  10. 10conn = psycopg2.connect(database='mydb')
  11. 11cur = conn.cursor()
  12. 12try:
  13. 13 cur.execute('SELECT * FROM mytable')
  14. 14finally:
  15. 15 cur.close() # Close the cursor here, but in a finally block
  16. 16 print(cur) # The cursor is still open and can be used

Example Code Solution

❌ Before (problematic code)
Python
import psycopg2

conn = psycopg2.connect(database='mydb')
cur = conn.cursor()
try:
    cur.execute('SELECT * FROM mytable')
    cur.close()
    cur.execute('SELECT * FROM another_table')
✅ After (fixed code)
Python
import psycopg2

conn = psycopg2.connect(database='mydb')
cur = conn.cursor()
try:
    cur.execute('SELECT * FROM mytable')
    cur.close()
    cur = conn.cursor() # Create a new cursor
    cur.execute('SELECT * FROM another_table')

Fix for psycopg2.errors.InvalidCursorName: cursor is closed

Related PYTHON Errors

Related PYTHON Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error