如何删除SQLAlchemy中的表?

时间:2016-03-10 14:01:07

标签: python sqlite sqlalchemy drop-table

我想使用SQLAlchemy删除表。

由于我一遍又一遍地进行测试,我想删除表my_users,这样我就可以每次都从头开始。

到目前为止,我使用SQLAlchemy通过engine.execute()方法执行原始SQL:

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

但是,我想知道是否有一些标准方法可以这样做。我能找到的唯一一个是drop_all(),但它删除了所有结构,而不仅仅是一个特定的表:

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

例如,给出这个非常基本的例子。它包含一个带有单个表my_users的SQLite基础结构,我在其中添加了一些内容。

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()会起作用,但从我开始拥有多个表的那一刻开始我就不方便了。我希望保留其他表。

5 个答案:

答案 0 :(得分:37)

只需针对表格对象调用drop()即可。 来自the docs

  

使用给定的Connectable进行连接,为此Table发出DROP语句。

在你的情况下应该是:

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

你需要传递引擎:

User.__table__.drop(engine)

答案 1 :(得分:10)

调用cls.__table__.drop(your_engine)的替代方法,你可以试试这个:

Base.metadata.drop_all(bind=your_engine, tables=[User.__table__])

此方法以及create_all()方法接受可选参数tables,该参数采用sqlalchemy.sql.schema.Table个实例的迭代器。

您可以通过这种方式控制要创建或删除的表。

答案 2 :(得分:5)

这是@Levon 答案的更新,因为 MetaData(engine, reflect=True) 现在已被弃用。如果您无权访问表类或想按表名删除表,这将很有用。

from sqlalchemy import MetaData
from sqlalchemy import create_engine
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.declarative import declarative_base

DATABASE = {
   'drivername': 'sqlite',
   # 'host': 'localhost',
   # 'port': '5432',
   # 'username': 'YOUR_USERNAME',
   # 'password': 'YOUR_PASSWORD',
   'database': '/path/to/your_db.sqlite'
}

engine = create_engine(URL(**DATABASE))

def drop_table(table_name, engine=engine):
    Base = declarative_base()
    metadata = MetaData()
    metadata.reflect(bind=engine)
    table = metadata.tables[table_name]
    if table is not None:
        Base.metadata.drop_all(engine, [table], checkfirst=True)

drop_table('users')

否则,您可能更喜欢使用 cls.__table__.drop(engine)cls.__table__.create(engine),例如

User.__table__.drop(engine)
User.__table__.create(engine)

答案 3 :(得分:3)

下面是您可以在iPython中执行的示例代码,用于测试Postgres上表的创建和删除

from sqlalchemy import * # imports all needed modules from sqlalchemy

engine = create_engine('postgresql://python:python@127.0.0.1/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

您还可以使用相同的示例和屏幕截图预览我在Wordpress上的文章:oscarvalles.wordpress.com(搜索SQL Alchemy)。

答案 4 :(得分:0)

在特殊情况下,当您无权访问表类并且只需要按表名删除表时,可以使用此代码

import logging
from sqlalchemy import MetaData
from sqlalchemy import create_engine
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.declarative import declarative_base

DATABASE = {
   'drivername': 'sqlite',
   # 'host': 'localhost',
   # 'port': '5432',
   # 'username': 'YOUR_USERNAME',
   # 'password': 'YOUR_PASSWORD',
   'database': '/path/to/your_db.sqlite'
}

def drop_table(table_name):
   engine = create_engine(URL(**DATABASE))
   base = declarative_base()
   metadata = MetaData(engine, reflect=True)
   table = metadata.tables.get(table_name)
   if table is not None:
       logging.info(f'Deleting {table_name} table')
       base.metadata.drop_all(engine, [table], checkfirst=True)

drop_table('users')