user19143736
user19143736

Reputation:

How can I drop this table using SQLAlchemy?

I am trying to drop a table called 'New'. I currently have the following code:

import pandas as pd
import sqlalchemy

sqlcon = sqlalchemy.create_engine('mssql://ABSECTDCS100TL/AdventureWorks?driver=ODBC+Driver+17+for+SQL+Server')3

df = pd.read_sql_query('SELECT * FROM DimReseller', sqlcon)

df.to_sql('New',sqlcon,if_exists='append', index=False)

sqlalchemy.schema.New.drop(bind=None, checkfirst=False)

I am receiving the error:

AttributeError: module 'sqlalchemy.schema' has no attribute 'New'

Any ideas on what I'm missing here?. Thanks.

Upvotes: 0

Views: 3472

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55933

You can reflect the table into a Table object and then call its drop method:

from sqlalchemy import Table, MetaData

tbl = Table('New', MetaData(), autoload_with=sqlcon)
tbl.drop(sqlcon, checkfirst=False)

If you want to delete the table using raw SQL, you can do this:

from sqlalchemy import text

with sqlcon.connect() as conn:
    # Follow the identifier quoting convention for your RDBMS
    # to avoid problems with mixed-case names.
    conn.execute(text("""DROP TABLE "New" """))
    # Commit if necessary
    conn.commit()

Upvotes: 2

Related Questions