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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…