Skip to main content
 首页 » 编程设计

python之SqlAlchemy automap 不生成 Base.classes.[table_name]

2025年02月15日38qq78292959

我有一个现有的 sqlite 数据库 file从 csv 导入。我尝试使用 sqlalchemy 自动映射数据库文件。但它总是给我...

追溯(最近的调用最后): 文件“”,第 1 行,位于 文件“C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sqlalchemy\util_colle ctions.py”,第 212 行,在 getattr 中 提高 AttributeError(键) 属性错误:目的地服务

感谢任何帮助。

from flask import Flask 
from flask_sqlalchemy import SQLAlchemy 
 
app = Flask(__name__) 
 
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:///destServ.db") 
 
# reflect the tables 
Base.prepare(engine, reflect=True) 
 
# mapped classes are now created with names by default 
# matching that of the table name. 
Service = Base.classes.destinationServices 

请您参考如下方法:

请原谅我回答一个老问题,但发生这种情况的原因是因为反射能力的限制,而且它更经常出现在 SQLite 数据库中,因为它们往往过于简单。要使 automap_base 工作,您需要确保您的 SQLite 数据库表有一个具有唯一值的主键(是的,这听起来多余,但显然它们在 SQLite 中有不同的含义?)。

如果您使用的是 SQLite 数据库浏览器(https://sqlitebrowser.org/ -- 适用于 Mac 和 Windows),您可以单击“数据库结构”选项卡,单击表名,然后单击“修改表”子选项卡应该在主选项卡正下方的辅助选项卡中可见(用户界面有点奇怪)。

进入“修改表”弹出窗口后,找到表的主键并确保选中 PK 和 U 框(对于主键和独特)。当您在那里时,您可以借此机会确保您的列具有合理的类型(例如,确保数字列使用正确的数字类型)。完成后单击“确定”。

正确定义数据库后,print(Base.classes.keys()) 应该会显示数据库中的所有表。