from pathlib import Path
from sqlalchemy import create_engine,Column, Integer, String
from sqlalchemy.orm import Session,declarative_base
engine = create_engine('sqlite://' + str(Path.cwd()) / 'test.db3')
session = Session(engine)
Base = declarative_base()
class Test(Base)
__tablename__ = 'test'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(string(255))
def __init__(self, name):
self.name = name
print(Base.metadata.tables) # 这里返回的数据与Test.__table__一致
Base.metadata.drop_all(engine, [Test.__table__])
Test.__table__.create(engine)
session.add(Test('a'))
session.commit
session.close
最后一段还可以写为
with Sessin(engine) as session:
session.add(Test('a'))
session.commit()