NameError: name 'con_db' 未定义

时间:2021-01-07 14:20:20

标签: python psycopg2

我有一个python脚本在Ubuntu远程server.Its运行试图连接到远程的Postgres。但我得到的名字error.I将运行:用cron job.My这个剧本是我的代码:

import psycopg2
try:

    conn_db =psycopg2.connect( user ="user",
    password="password",
    host="95.78.45.78",
    port="5432",
    database="database"
    )
    

    cursor =conn_db.cursor()
   

    cursor.execute("""CREATE TABLE test(
                    id SERIAL,store VARCHAR(50),app VARCHAR(50),event_count BIGINT, peak_hour timestamp) """)


    cursor.execute("""    
    INSERT INTO test(app,store,event_count,peak_hour) select distinct on (app, store) 
        app, store,
        count(*) as event_count,
        date_trunc('hour', createdat) as peak_hour
    from test_table
    group by app, store, peak_hour
    order by store, event_count desc """)
    conn_db.commit()
    count = cursor.rowcount
    print(count, "Record inserted successfully into test_table")


except(Exception, psycopg2.Error) as error :

    if(conn_db):
        print("Failed to insert record into test_table", error)   

finally:

    if(conn_db):
        cursor.close()
        conn_db.close()
        print("PostgreSQL connection is closed")

这就是我的错误:

Traceback (most recent call last):
  File "test.py", line 41, in <module>
    if(conn_db):
NameError: name 'conn_db' is not defined

1 个答案:

答案 0 :(得分:1)

在您调用 psycopg2.connect() 时,数据库是不推荐使用的别名。

能否用dbname 替换它并再次运行。

conn_db 可以全局初始化为 None