英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论