psycopg2:“ UnboundLocalError”,“ evalue”:“分配前引用的本地变量'连接'

问题描述

我有一个psycopg2连接,用于从pyspark连接到postgresql。这是我的代码-

host = 'IP Address'
port = 'Port'
user = 'postgres'
db = 'postgres'
password = 'password'

def move_records(main_table,stg_table):
    try: 
        connection = psycopg2.connect(host=host,database=db,user=user,password=password,#driver = driver,port = port)
        cursor = connection.cursor()
        move_query = "INSERT INTO " +main_table+ " select * from "+stg_table+" where country ='USA'"
        cursor.execute(move_query)
        connection.commit()
        logger.debug("Record moved successfully")
    except (Exception,psycopg2.DatabaseError) as error :
        logger.error("%s Error in transction Reverting all other operations of a transaction ",error)
        global flag
        flag = False
        connection.rollback()
    finally:
        if(connection):
            cursor.close()
            connection.close()
            logger.debug("Postgresql connection is closed")

move_records(table_1,table_2)

但是我一直在if(connection)的行下面得到错误提示

"UnboundLocalError","evalue":"local variable 'connection' referenced before assignment"

无法弄清楚是什么问题。需要帮助。

解决方法

我不是Python专家,但我从事类似的工作,使用psycopg2在AWS Lambda中将Python连接到Postgres。

我认为错误在于变量范围内。您需要再次在函数内将所有变量(主机,端口,用户,数据库,密码)声明为 global nonlocal ,然后尝试运行功能。

供参考,请查看此link:-