基于PostgreSQL数据库的Python SQL查询

2024-10-04 11:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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)时,它似乎会进入异常。 我没有错误消息。但是使用计数数据的查询正在运行。。。 谢谢


Tags: 代码nameformaturlexecutedbcounttable
1条回答
网友
1楼 · 发布于 2024-10-04 11:22:31

我认为错误的原因是表上有外键。为确保安全,请将异常分配到变量并打印:

except Exception as ex:
    print(ex)

顺便说一下,如果您想快速删除表中的所有行,那么 使用truncate表而不是删除所有行将更有效率: truncate table table_name

在某些情况下要删除行时,“删除”更有用: delete from table_name where ...

相关问题 更多 >