我如何在Sqlalchemy中没有主键的情况下在表格上查询?
我需要从没有主键的情况下从表中获取数据。 我做了以下操作以使其可见/映射,但是我仍然无法通过它查询。 这是我的代码:
table = 'my_table'
db_tables = automap_base()
metadata = MetaData()
my_table = Table(table, db_tables.metadata, Column('row_id', Integer, primary_key=True), autoload=True, autoload_with=db.engine)
db_tables.prepare(db.engine, reflect=True)
#
data = db.session.query(db_tables.classes.my_table).filter(
db_tables.classes.my_table.device_name.like('%uni%'),
)
以下操作时,代码崩溃:
注意'.all()'
db.session.query(db_tables.classes.my_table).filter(
db_tables.classes.my_table.device_name.like('%uni%'),
).all()
或
data.all()
当我执行
for row in data:
row.name
这是我遇到的错误:
{programMingerRor}(pyodbc.programmingerror)('42S22',“ [42S22] [Microsoft] [SQL Server的ODBC驱动程序17] [SQL Server]无效列 名称“ row_id”。 (207)(sqlexecdirectw)”)
I need to get data from a table without primary key.
I did the following to make it visible/mappable, however I still can't query through it.
This is my code:
table = 'my_table'
db_tables = automap_base()
metadata = MetaData()
my_table = Table(table, db_tables.metadata, Column('row_id', Integer, primary_key=True), autoload=True, autoload_with=db.engine)
db_tables.prepare(db.engine, reflect=True)
#
data = db.session.query(db_tables.classes.my_table).filter(
db_tables.classes.my_table.device_name.like('%uni%'),
)
The code crashes when I do the following:
Notice '.all()'
db.session.query(db_tables.classes.my_table).filter(
db_tables.classes.my_table.device_name.like('%uni%'),
).all()
Or
data.all()
Or
for row in data:
row.name
This is the error I get:
{ProgrammingError}(pyodbc.ProgrammingError) ('42S22', "[42S22]
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column
name 'row_id'. (207) (SQLExecDirectW)")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Sqlalchemy(以及我使用过的所有ORM)需要一个主要的操作键。
但是,该主键不需要将其设置为数据库中的主键,如果您没有天然键,则可以在反射表上定义它为单列,如果不这样使用完整行作为主键)。
您将
row_id
设置为主要密钥,是否存在于表中?如果不是,则需要在现有列上设置另一个主题。
http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-do-i-i-i-map-a-table-table-table-table-table-that-has-no-primary-key
SQLAlchemy (and all ORMs that I have used) needs a primary key to operate.
That primary key however doesn’t need to be set as primary key in the database, you can define it on a reflected table as a single column if you have a natural key, or a group of columns if you don’t (up to using the full row as primary key).
You’re setting
row_id
as your primary key, does it exist in the table ?If not, you need to set another primary on existing columns.
http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key
在使用SA查询MySQL时,您可以简单地进行:
然后迭代结果,并选择您要寻找的内容。
对于查询数据,您不需要知道主键,SA应该为您照顾
When querying MYSQL using SA you can simply do:
Then iterate over the results if any and choose what you were looking for.
For querying data you do not need to know the primary key, SA is supposed to take care of that for you