将已设计的mysql表映射到sqlachemy

2024-06-01 14:45:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我来自这样一个地方:数据库设计者/管理员给你一个MySQL数据库,它已经设计好了所有的表,还有函数、触发器等,你所要做的就是对表执行CRUD。你知道吗

所以我想知道是否有一种方法可以使用sqlachemy映射到已经设计好的表,并使用sqlachemy方法对表执行CRUD,而不必使用我的python代码创建表(因为我没有权限)基本上避免了以下步骤:

metadata = MetaData()
books = Table('book', metadata,
  Column('id', Integer, primary_key=True),
  Column('title', String),
  Column('primary_author', String),
)

engine = create_engine('sqlite:///bookstore.db')
metadata.create_all(engine)

注意:我使用一个sqlite示例来说明我的观点。 谢谢


Tags: 方法数据库sqlitestring管理员地方createmysql
1条回答
网友
1楼 · 发布于 2024-06-01 14:45:40

嗨,请看一下SQLAlchemyAutomap。它也许能起作用

显然,这似乎还不够:

from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine

Base = automap_base()

# engine, suppose it has two tables 'user' and 'address' set up
engine = create_engine("sqlite:///mydatabase.db")

# reflect the tables
Base.prepare(engine, reflect=True)

# mapped classes are now created with names by default
# matching that of the table name.
User = Base.classes.user
Address = Base.classes.address

然后你可以直接做你的CRUD操作,比如添加,更新等等。。。你知道吗

相关问题 更多 >