SQLAlchemy 选择

问题描述 投票:0回答:1

select方法必须以with alchemy为前缀。

import sqlalchemy as alchemy
from sqlalchemy import select, text, column, values

s = alchemy.select(cookies.c.cookie_name,
                       cookies.c.quantity)

“select”已从 sqlalchemy 导入,但有必要为 sqlalchemy 添加导入语句,并使用导入名称“alchemy”限定“select”。 如果没有限定的 select,(alchemy.select(...),就会出现错误“select 方法有两个很多参数”

问题是为什么?

import sqlalchemy as alchemy
from sqlalchemy import select, text, column, values

def queries_selected_columns(connection, metadata):
    """
    Select only a couple of columns to retrieve from the cookies table.
    """

    # Retrieve the cookies table object from the metadata
    cookies = metadata.tables["cookies"]

    # Build the SQL statement
    # s = cookies.select(cookies.c.cookie_name, cookies.c.quantity)
    s = alchemy.select(cookies.c.cookie_name,
                       cookies.c.quantity)
    rp = connection.execute(s)  # Create the result proxy
    print("\nFetch the cookie name and quantity")
    print(rp.keys())
    result = rp.first()
    print(f"result: {result}")

仅使用“select(...)”而不使用“alchemy.select(...)”时的错误

TypeError: FromClause.select() takes 1 positional argument but 3 were given


 (venv) E:\www\sandbox\alchemy\playground>python main.py
Traceback (most recent call last):
  File "E:\www\sandbox\alchemy\playground\main.py", line 21, in <module>
    queries_selected_columns(connection, metadata)
  File "E:\www\sandbox\alchemy\playground\db_querries.py", line 111, in queries_selected_columns
    s = cookies.select(cookies.c.cookie_name, cookies.c.quantity)
TypeError: FromClause.select() takes 1 positional argument but 3 were given      

(venv) E:\www\sandbox\alchemy\playground>
select import sqlalchemy
1个回答
0
投票

当您调用

cookies.select
时,您正在调用表对象的 select 方法。此方法比 sqlalchemy.select 更受限制 - 它仅选择表中的所有列。因此,调用时不需要任何参数。

© www.soinside.com 2019 - 2024. All rights reserved.