我在Postgres ElephantSql主机上运行SQL查询时遇到问题: 这是我要连接的代码(除了dynamo、用户、密码,它们被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)时,它似乎会进入异常。 我没有错误消息。但是使用计数数据的查询正在运行。。。 谢谢
我认为错误的原因是表上有外键。为确保安全,请将异常分配到变量并打印:
顺便说一下,如果您想快速删除表中的所有行,那么 使用
truncate
表而不是删除所有行将更有效率:truncate table table_name
在某些情况下要删除行时,“删除”更有用:
delete from table_name where ...
相关问题 更多 >
编程相关推荐