Python通过sqlalchemy创建Postgresql表,然后删除该选项卡

2024-04-19 04:24:07 发布

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

我通过Sqlalchemydf.to_sql()创建postgresql数据库表,但当我删除该表时,它不会被删除

conn = psycopg2.connect(user='postgres', password='Shubham@123', 
       host='localhost', port='5432', database='upload')
cur = conn.cursor()

engine = create_engine('postgresql://postgres:Shubham@123@localhost:5432/upload')
table_name = "demo_table"
df.to_sql(table_name, engine, index=False)

table_exists = """select exists(select * from information_schema.tables where 
                table_name = '{}')""".format(table_name)
cur.execute(table_exists)
exists = cur.fetchone()[0]

if exists == True:
   print(table_name)
   delete_table = """Drop Table if exists "{}" """.format(table_name)
   print(delete_table)
   cur.execute(delete_table)
   conn.commit()

预期的输出是,它应该删除已创建的表


Tags: tonamelocalhostsqlpostgresqlexiststablepostgres