如何在Python的if语句中将PostgreSQL布尔值用作参数?

huangapple go评论58阅读模式
英文:

How to use a Postgreql Boolean value as a parameter in a python if statement?

问题

我一直在尝试创建一个Python函数,该函数将使用选择语句从我的Postgres数据库中返回一个布尔值,并将其用于Python的if语句中。

我发现当打印SQL选择语句的结果时,格式是[(True,)]。然而,我尝试放入Python的if语句中的任何内容都没有起作用。
我尝试过:

True
"True"
"[(True,)]"
"[" + str(True) + ",]"

这些都没有起作用,我真的想不出还可能是什么。

我执行的SQL语句是:

cur = conn.cursor()
cur.execute("SELECT is_draft FROM item_pool WHERE item_id = " + str(item_id) + " ", {})
list_of_tuples = cur.fetchall()
conn.close()
return list_of_tuples

我想检查在Python中返回的is_draft布尔值是否为True。

英文:

I have been trying to create a python function that will use a select statement that will return a single Boolean value from my postgres database and then use it in a python if statement.

I have found out that when you print the result of the sql select statemtent the format is [(True,)]. However, nothing that I have tried putting in the python if statement has not worked.
I have tried:

True
"True"
"[(True,)]"
"[(" + str(True) + ",)]"

and none of these have worked and I can't really think of what else it could be.

The sql statement I am executing is

cur = conn.cursor()
cur.execute("SELECT is_draft FROM item_pool WHERE item_id = " + str(item_id) + " ", {})
list_of_tuples = cur.fetchall()
conn.close()
return list_of_tuples

And I want to check if the is_draft Boolean that is returned is True in python.

答案1

得分: 0

您的函数将返回

    return cursor.fetchone()[0]

这将返回 `TRUE``FALSE`

对于类似的查询

    SELECT EXISTS(SELECT 1 FROM mytable WHERE id = -1)
英文:

In python

your function would return

return cursor.fetchone()[0]

which would return TRUE or FALSE

for a query like

SELECT EXISTS(SELECT 1 FROMmytable WHERE id = -1)

huangapple
  • 本文由 发表于 2023年2月16日 06:53:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定