我有一个问题来运行我的SQL查询在Postgres ElephantSql托管:这是我的代码连接(除了发电机,用户,密码,它们被XXX取代
DATABASE_URL = 'postgres://YYYY:ZZZZ@drona.db.elephantsql.com:5432/YYYY'
# ---------------------------- CONNECT ELEPHANT DB
def ElephantConnect():
up.uses_netloc.append("postgres")
url = up.urlparse(DATABASE_URL)
conn = psycopg2.connect(dbname='YYYY',
user='YYYY',
password='ZZZZ',
host='drona.db.elephantsql.com',
port='5432'
)
cursor = conn.cursor()
# cursor.execute("CREATE TABLE notes(id integer primary key, body text, title text);")
#conn.commit()
# conn.close()
return conn 这段代码似乎与db连接得很好。
我的问题是当我想删除一个表的时候:
def update(df, table_name, deleteYes= 'Yes'):
conn = ElephantConnect()
db = create_engine(DATABASE_URL)
cursor =conn.cursor()
if deleteYes == 'Yes': # delete
queryCount = "SELECT count(*) FROM {};".format(table_name)
queryDelete = "DELETE FROM {};".format(table_name)
count = db.execute(queryCount)
rows_before = count.fetchone()[0]
try:
db.execute(queryDelete)
logging.info('Deleted {} rows into table {}'.format(rows_before, table_name))
except:
logging.info('Deleted error into table {}'.format(table_name))
else:
pass似乎当我运行db.execute(queryDelete)时,它转到了异常。我没有错误的消息。但是使用计数数据的查询是有效的...谢谢
发布于 2020-04-03 21:36:03
我认为错误的原因是因为表中有外键。为了确保这一点,将异常赋给一个变量并打印出来:
except Exception as ex:
print(ex)顺便说一下,如果您想要快速删除表中的所有行,那么使用truncate表将比删除所有行效率高得多:truncate table table_name
在某些情况下,当您想要删除行时,Delete更有用:delete from table_name where ...
https://stackoverflow.com/questions/60920237
复制相似问题