2016-03-10 98 views
12

SQLAlchemyを使用してテーブルを削除します。SQLAlchemyでテーブルを削除するには?

何度も何度も試していますので、テーブルmy_usersを削除して、毎回ゼロから始めることができます。これまでのところ、私はengine.execute()メソッドを介して生のSQLを実行するためのSQLAlchemyのを使用しています

:そうするためのいくつかの標準的な方法があるかどう

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

はしかし、私は疑問に思います。私は見つけることができる唯一のdrop_all()ですが、それはすべての構造を削除し、ある特定のテーブルだけではなく、例えば:

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

、この非常に基本的な例を与えます。これは、SQLiteインフラストラクチャと単一のテーブルmy_usersで構成されており、そこにはいくつかのコンテンツが追加されています。この特定のケースでは

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) 

drop_all()は動作しますが、それは私が複数のテーブルを持ち始めると、私は他のものを維持したい瞬間から、便利ではありません。

答えて

19

drop()をテーブルオブジェクトに対して呼び出してください。 the docsから:あなたのケースでは

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

それは次のようになります。

User.__table__.drop() 

あなたが取得する場合のような例外:あなたはエンジンを渡す必要が

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 

以下は
+2

興味深い!しかし、 'User .__ table __。drop()'を追加すると、エラーが発生します。 'sqlalchemy.exc.UnboundExecutionError:テーブルオブジェクト 'my_users'がエンジンまたは接続にバインドされていません。実行するデータベースがなければ実行できません。それは合理的だと思うが、私はこれを行うためにエンジンやセッションを使用する方法を知らない。 – fedorqui

+3

@fedorqui drop()の引数としてエンジンを渡してみてください。 – daveoncode

+5

ああ男 'User .__ table __。drop(engine)'それを作った、多くの感謝! – fedorqui

1

あなたはまた、同じ例とスクリーンショットでWordpressの上の私の記事をプレビューすることができPostgresの

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 

に、テーブルの作成と削除をテストするためにiPythonに実行できるサンプルコードです:oscarvalles.wordpress。 com(SQL Alchemyを検索する)。

関連する問題