Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

python - NameError: name 'con_db' is not defined

I have a python script running in ubuntu remote server.Its trying connect to a remote postgres .But I am getting name error.I will run the script with cron job.My This is my code:

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")

Thats my error:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your call psycopg2.connect(), database is a deprecated alias.

Can you replace it with dbname and run once again please.

conn_db can be globally intialized as None


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...