执行sqlalchemy存在查询

时间:2017-06-05 01:43:01

标签: python sqlalchemy exists

我无法理解如何执行查询以检查并查看sqlalchemy中是否已存在匹配的记录。我在网上找到的大多数例子都可以参考" session"和"查询"我没有的物品。

这是一个简短的完整程序,用于说明我的问题:
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>

4 个答案:

答案 0 :(得分:6)

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())

答案 1 :(得分:0)

SQL子查询中使用了

exists。如果您的表posts包含带有author_id的博文,并映射回给人,您可以使用如下查询来查找撰写博客文章的人:

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

您不能将exists作为SQL查询中的最外层语句;它是在SQL布尔子句中使用的运算符。 因此,SQLAlchemy不允许您执行该查询,因为它的格式不正确。 如果要查看是否存在行,只需构造带有where子句的select语句,并查看查询返回的行数。

答案 2 :(得分:0)

请改为尝试:

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

答案 3 :(得分:0)

除非有人建议更好的答案,否则我的想法就是这样。让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