我想使用 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
例如,给出这个非常基本的例子。它由一个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()
会起作用,但是从我开始拥有多个表并且我想保留其他表的那一刻起,它就不方便了。
只需对表对象调用drop()
即可。从文档中:
为此表发出 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)
调用cls.__table__.drop(your_engine)
的替代方法,您可以尝试:
Base.metadata.drop_all(bind=your_engine, tables=[User.__table__])
此方法以及 create_all()
方法接受可选参数 tables
,该参数接受sqlalchemy.sql.schema.Table
实例的迭代器。
您可以控制以这种方式创建或删除哪些表。
表类并且只需要按表名删除表的特殊情况,请使用此代码
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')
如何按名称删除表
这是@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)
下面是您可以在 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)。