sqlalchemy 判断表是否存在,执行sqlalchemy存在查询

I'm having trouble understanding how to execute a query to check and see if a matching record already exists in sqlalchemy. Most of the examples I can find online seem to reference "session" and "query" objects that I don't have.

Here's a short complete program that illustrates my problem:

1. sets up in-memory sqlite db with "person" table.

2. inserts two records into the person table.

3. check if a particular record exists in the table. This is where it 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)

The output of this program is:

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

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:

解决方案

The s.exists() is only building the exists clause. All you need to do to get your code to work is to generate a select for it.

s = exists(s).select()

Here's your full example:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值