Python 名称错误:名称';con#u db';没有定义
我在ubuntu远程服务器上运行了一个python脚本。它正在尝试连接到远程postgres。但我收到了名称错误。我将使用cron作业运行该脚本。我的代码是:Python 名称错误:名称';con#u db';没有定义,python,psycopg2,Python,Psycopg2,我在ubuntu远程服务器上运行了一个python脚本。它正在尝试连接到远程postgres。但我收到了名称错误。我将使用cron作业运行该脚本。我的代码是: import psycopg2 try: conn_db =psycopg2.connect( user ="user", password="password", host="95.78.45.78", port="5432"
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
回溯(最近一次呼叫最后一次):
文件“test.py”,第41行,在
如果(连接数据库):
NameError:未定义名称“conn_db”
在调用psycopg2.connect()时,数据库是不推荐使用的别名
您能用dbname替换它并再次运行吗
conn_db可以全局初始化为None您正在捕获一个错误,其中连接创建失败,因此尚未定义。您可以在尝试之前放置
conn_db=None
,您将得到不同的错误。