Home > Software design >  This name error keeps popping up despite me importing the relevant library- // cur = conn.cursor()//
This name error keeps popping up despite me importing the relevant library- // cur = conn.cursor()//

Time:08-20

cur = conn.cursor() conn is not defined 

I have imported psycopg2 and therefore, the conn module should be recognised. Below is my script if needs be.

# Small script to show PostgreSQL and Pyscopg together
import psycopg2

connection_to_db = psycopg2.connect("dbname='XYZ' user='XYZ' host='localhost' password='XYZ'")

try:
   if connection_to_db:
    print("Logged in")
except:
    print("I am unable to connect to the database")


cur = conn.cursor()
cur.execute("SELECT ** FROM weather ")

CodePudding user response:

Conn is not defined here. Either change connection_to_db to be conn or define it as a context manager. A benefit of context managers is that you don't have to close the connection manually

with psycopg2.connect("dbname='XYZ' user='XYZ' host='localhost' password='XYZ'") as conn:
    with conn.cursor() as cur:
        cur.execute("SELECT ** FROM weather ")
  • Related