python-3.x 如何使用table.drop(engine,checkfirst=True)该高速缓存?

cx6n0qe3  于 2023-05-08  发布在  Python
关注(0)|答案(1)|浏览(164)

bounty还有6天到期。回答此问题可获得+50声望奖励。showkey正在寻找一个答案从一个有信誉的来源

列出数据库sample中的所有表:

from sqlalchemy import (MetaData, Table)
from sqlalchemy import create_engine, inspect
db_pass = 'xxxxxx'
db_ip='127.0.0.1'
engine = create_engine('postgresql://postgres:{}@{}/sample'.format(db_pass,db_ip))
inspector = inspect(engine)
print(inspector.get_table_names())
['pre', 'sample']

现在删除表pre

metadata = MetaData()
pre_table = Table('pre', metadata)
pre_table.drop(engine, checkfirst=True)

进入psql时输入\dsample数据库中只显示一个表:

psql -U postgres
postgres=# \c  sample
You are now connected to database "sample" as user "postgres".
sample=# \d
public | sample                       | table    | postgres

pre已删除!但是print(inspector.get_table_names())(第二次输入)仍然显示数据库中的两个表:

print(inspector.get_table_names())
['pre', 'sample']

如何使用table.drop(engine,checkfirst=True)该高速缓存?

ni65a41a

ni65a41a1#

您可以通过创建inspector对象的新示例来“清除该高速缓存”:

import sqlalchemy as sa

engine = sa.create_engine("postgresql://scott:tiger@192.168.0.199/test")
table_name = "so76151021"

with engine.begin() as conn:
    conn.exec_driver_sql(f"DROP TABLE IF EXISTS {table_name}")
    conn.exec_driver_sql(f"CREATE TABLE {table_name} (id int)")

inspector = sa.inspect(engine)
print(inspector.get_table_names())
# ['so76151021']

tbl = sa.Table(table_name, sa.MetaData(), autoload_with=engine)
tbl.drop(engine, checkfirst=True)

print(inspector.get_table_names())
# ['so76151021']

inspector = sa.inspect(engine)  # create new instance
print(inspector.get_table_names())
# []

相关问题