如何解决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:-
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。