2016-03-10 21 views
12

Chcę usunąć tabelę przy użyciu SQLAlchemy.Jak usunąć tabelę w SQLAlchemy?

Ponieważ testuję w kółko, chcę usunąć tabelę my_users, dzięki czemu mogę zacząć od początku za każdym razem.

Dotychczas Używam SQLAlchemy wykonać surowego SQL za pomocą metody engine.execute():

sql = text('DROP TABLE IF EXISTS my_users;') 
result = engine.execute(sql) 

, zastanawiam się jednak, czy istnieje jakiś standardowy sposób, aby to zrobić. Tylko jeden udało mi się znaleźć to drop_all(), ale usuwa wszystkie struktury, a nie tylko jedną konkretną tabelę:

Base.metadata.drop_all(engine) # all tables are deleted 

Na przykład, mając to bardzo prosty przykład. Składa się z infrastruktury SQLite z pojedynczą tabelą my_users, w której dodaję trochę treści.

from sqlalchemy import create_engine, Column, Integer, String, text 
from sqlalchemy.orm import sessionmaker 
from sqlalchemy.ext.declarative import declarative_base 

engine = create_engine('sqlite://', echo=False) 
Base = declarative_base() 

class User(Base): 
    __tablename__ = "my_users" 

    id = Column(Integer, primary_key=True) 
    name = Column(String) 

    def __init__(self, name): 
     self.name = name 

# Create all the tables in the database which are 
# defined by Base's subclasses such as User 
Base.metadata.create_all(engine) 

# Construct a sessionmaker factory object 
session = sessionmaker() 

# Bind the sessionmaker to engine 
session.configure(bind=engine) 

# Generate a session to work with 
s = session() 

# Add some content 
s.add(User('myname')) 
s.commit() 

# Fetch the data 
print(s.query(User).filter(User.name == 'myname').one().name) 

W tym konkretnym przypadku, drop_all() będzie działać, ale nie będzie to wygodne od chwili, kiedy zaczniemy mieć więcej niż jedną tabelę i chcę zachować pozostałych.

Odpowiedz

19

Po prostu zadzwoń pod numer drop() na obiekt tabeli. Od the docs:

Issue a DROP statement for this Table, using the given Connectable for connectivity.

w Twoim przypadku powinno być:

User.__table__.drop() 

Jeśli pojawi się wyjątek jak:

sqlalchemy.exc.UnboundExecutionError: Table object 'my_users' is not bound to an Engine or Connection. Execution can not proceed without a database to execute against 

Trzeba zdać silnik:

User.__table__.drop(engine) 
+2

Interesujące! Jednak jeśli dodaję tabelę "User .__" __. Drop() 'pojawia się błąd:' sqlalchemy.exc.UnboundExecutionError: Obiekt tabeli 'my_users' nie jest powiązany z silnikiem lub połączeniem. Wykonanie nie może być kontynuowane bez bazy danych do wykonania przeciwko. Wygląda to rozsądnie, ale nie wiem, jak to zrobić za pomocą silnika lub sesji. – fedorqui

+3

@fedorqui Spróbuj przekazać silnik jako argument do drop(), i daj mi znać – daveoncode

+5

Oh man 'User .__ table __. Drop (engine)' made it, many thanks! – fedorqui

1

Poniżej jest przykład kodu można wykonać w ipython przetestować tworzenie i usuwanie tabeli na PostgreSQL

from sqlalchemy import * # imports all needed modules from sqlalchemy 

engine = create_engine('postgresql://python:[email protected]/production') # connection properties stored 

metadata = MetaData() # stores the 'production' database's metadata 

users = Table('users', metadata, 
Column('user_id', Integer), 
Column('first_name', String(150)), 
Column('last_name', String(150)), 
Column('email', String(255)), 
schema='python') # defines the 'users' table structure in the 'python' schema of our connection to the 'production' db 

users.create(engine) # creates the users table 

users.drop(engine) # drops the users table 

Można również podejrzeć mój artykuł na Wordpress z tym samym przykład i screeny: oscarvalles.wordpress. com (wyszukaj SQL Alchemy).