簡體   English   中英

執行sqlalchemy存在查詢

[英]Executing a sqlalchemy exists query

我無法理解如何執行查詢以檢查並查看sqlalchemy中是否已存在匹配的記錄。 我在網上找到的大多數例子似乎都引用了我沒有的“會話”和“查詢”對象。

這是一個簡短的完整程序,說明了我的問題:
1.使用“person”表設置內存中的sqlite數據庫。
2.將兩個記錄插入到人員表中。
3.檢查表中是否存在特定記錄。 這是barfs的地方。

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql.expression import exists

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

person = Table('person', metadata,
                        Column('id', Integer, primary_key=True),
                        Column('name', String(255), nullable=False))

metadata.create_all(engine)
conn = engine.connect()

s = person.insert()
conn.execute(s, name="Alice")
conn.execute(s, name="Bob")

print("I can see the names in the table:")
s = person.select()
result = conn.execute(s)
print(result.fetchall())

print('This query looks like it should check to see if a matching record exists:')
s = person.select().where(person.c.name == "Bob")
s = exists(s)
print(s)

print("But it doesn't run...")
result = conn.execute(s)

該程序的輸出是:

I can see the names in the table:
[(1, 'Alice'), (2, 'Bob')]
This query looks like it should check to see if a matching record exists:
EXISTS (SELECT person.id, person.name 
FROM person 
WHERE person.name = :name_1)
But it doesn't run...
Traceback (most recent call last):
  File "/project_path/db_test/db_test_env/exists_example.py", line 30, in <module>
    result = conn.execute(s)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 265, in _execute_on_connection
    raise exc.ObjectNotExecutableError(self)
sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: <sqlalchemy.sql.selectable.Exists object at 0x105797438>

s.exists()僅構建exists子句。 要使代碼工作,您需要做的就是為它生成一個選擇。

s = exists(s).select()

這是你的完整例子:

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql.expression import exists

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

person = Table('person', metadata,
                        Column('id', Integer, primary_key=True),
                        Column('name', String(255), nullable=False))

metadata.create_all(engine)
conn = engine.connect()

s = person.insert()
conn.execute(s, name="Alice")
conn.execute(s, name="Bob")

print("I can see the names in the table:")
s = person.select()
result = conn.execute(s)
print(result.fetchall())

print('This query looks like it should check to see if a matching record exists:')
s = person.select().where(person.c.name == "Bob")
s = exists(s).select()
print(s)

print("And it runs fine...")
result = conn.execute(s)
print(result.fetchall())

exists用於SQL子查詢中。 如果你有一個包含帶有author_id的博客文章的桌面posts ,並映射回給人們,你可以使用如下的查詢來查找創建博客文章的人:

select * from people where exists (select author_id from posts where author_id = people.id);

您不能將exists作為SQL查詢中的最外層語句; 它是在SQL布爾子句中使用的運算符。 因此,SQLAlchemy不允許您執行該查詢,因為它的格式不正確。 如果要查看是否存在行,只需使用where子句構造一個select語句,並查看查詢返回的行數。

試試這個:

...
s = person.select().where(person.c.name == "Bob")
s = select(exists(s))
print(s)
...

除非有人建議更好的答案,否則這就是我提出的有效方法。 讓DB計算匹配記錄並將計數發送到python應用程序。

from sqlalchemy import select, func   # more imports not in my example code above

s = select([func.count(1)]).select_from(person).where(person.c.name == "Bob")
print(s)
record_count = conn.execute(s).scalar()
print("Matching records: ", record_count)

示例輸出:

SELECT count(:count_2) AS count_1 
FROM person 
WHERE person.name = :name_1
Matching records:  1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM