NameError: name 'con_db' is not defined
NameError: name 'con_db' is not defined
我在 ubuntu 远程 server.Its 中有一个 python 脚本 运行ning 正在尝试连接到远程 postgres。但是我正在获取名称 error.I will 运行 带有 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
在您的调用 psycopg2.connect() 中,数据库是一个已弃用的别名。
你能用 dbname 和 运行 再次替换它吗?
conn_db 可以全局初始化为 None
我在 ubuntu 远程 server.Its 中有一个 python 脚本 运行ning 正在尝试连接到远程 postgres。但是我正在获取名称 error.I will 运行 带有 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
在您的调用 psycopg2.connect() 中,数据库是一个已弃用的别名。
你能用 dbname 和 运行 再次替换它吗?
conn_db 可以全局初始化为 None