[英]SQLAlchemy alternative names for table columns
我知道我的问题一定很简单,但我找不到任何直接的答案。
我正在使用 SQlAlchemy 映射一个表:
from sqlalchemy import Table, Column, Integer, String, MetaData, select
metadata = MetaData()
chicago_schools_manual = Table(
'chicago_schools', metadata,
Column('School ID', Integer, primary_key = True),
Column('Name of School', String))
如何为上面的现有列设置标签以避免它们的当前名称带有空格?
额外的问题:考虑到它们的内容/努力相似(但在类中更大一点),映射为类而不是映射为表的优势是什么?
编辑额外的疑问:
你能告诉我这个语句有什么问题,所以我不能将它用于简单的选择 where 吗? stmt = select(chicago_schools_manual).where(chicago_schools.columns['Name of School'] == 'Charles').limit(20)
Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
File c:\Users\fabio\AppData\Local\Programs\Python\Python310\lib\site-packages\ibm_db_dbi.py:1287, in Cursor._set_cursor_helper(self)
1286 try:
-> 1287 num_columns = ibm_db.num_fields(self.stmt_handler)
1288 except Exception as inst:
Exception: SQLNumResultCols failed: [IBM][CLI Driver][DB2/LINUXX8664] SQL0203N A reference to column "CHICAGO_SCHOOLS.Name of School" is ambiguous. SQLSTATE=42702 SQLCODE=-203
During handling of the above exception, another exception occurred:
ProgrammingError Traceback (most recent call last)
File c:\Users\fabio\AppData\Local\Programs\Python\Python310\lib\site-packages\sqlalchemy\engine\base.py:1819, in Connection._execute_context(self, dialect, constructor, statement, parameters, execution_options, *args, **kw)
1818 if not evt_handled:
-> 1819 self.dialect.do_execute(
...
[SQL: SELECT chicago_schools."School ID", chicago_schools."Name of School", chicago_schools."Safety Score", chicago_schools."Location"
FROM chicago_schools, chicago_schools
WHERE chicago_schools."Name of School" = ? FETCH FIRST 20 ROWS ONLY]
[parameters: ('Charles',)]
如果我按照建议的方式使用它:
stmt = select(chicago_schools_manual.c.Name_of_School).where(chicago_schools_manual.c.Name_of_School == 'Charles').limit(20)
您可以使用key="some_name"
通过与表中实际列名不同的名称来引用列。 例如,
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, select
engine = create_engine("sqlite://")
metadata = MetaData()
chicago_schools_manual = Table(
"chicago_schools",
metadata,
Column("School ID", Integer, primary_key=True, key="school_id"),
Column("Name of School", String, key="name_of_school"),
)
metadata.create_all(engine)
with engine.begin() as conn:
conn.execute(
chicago_schools_manual.insert(), dict(name_of_school="School #1")
)
"""SQL emitted:
INSERT INTO chicago_schools ("Name of School") VALUES (?)
[generated in 0.00032s] ('School #1',)
"""
with engine.begin() as conn:
results = conn.execute(
select(
chicago_schools_manual.c.school_id,
chicago_schools_manual.c.name_of_school,
)
).all()
print(results) # [(1, 'School #1')]
回复:奖金问题 - 见
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.