【问题标题】:Check PostgreSQL table column for value and return boolean检查 PostgreSQL 表列的值并返回布尔值
【发布时间】:2017-02-01 21:52:02
【问题描述】:

我只是在学习 SQL,如果重复,我深表歉意,但我已经搜索并没有找到答案。使用 PostgreSQL 数据库在 python 中编写。

我想检查我数据库中的一个表,看看“端口”列是否包含特定位置。我可以交互地执行此操作,但它会返回一个表格结果,例如:

select exists(select 1 from ref_locations where "Port"='ORAN');

它返回:

exists
-------
t
(1 row)

...我希望它只返回一个布尔值,并且我想在我的 python 脚本中执行它。在我的 python 脚本中,我有:

exists = False
cnx.execute("""select exists(select 1 from ref_locations where "Port"='BAKU');""")
print "Exists: ",exists

but exists 总是用 False 填充。非常感谢任何帮助。

【问题讨论】:

  • print "Exists: ",exists 您的存在变量不会被查询结果更改。您需要从查询中检索结果,并将其分配给您的变量。您的光标中可能有一些功能,例如exists = cnx.get_result();
  • 谢谢!很好的答案。至少在我解决这个问题的过程中,我意识到,由于我正在测试很多单词是否存在于我的“端口”表中,因此实际上将我的表读入哈希表或 pandas 表比每次都查询数据库。

标签: python mysql postgresql


【解决方案1】:

你的 postgresql 语句没有问题,虽然你可以把它缩短一点:

select exists(select from ref_locations where Port='ORAN');

您遇到的问题是执行语句的结果没有分配给任何东西。

考虑改为尝试这个(在您的执行语句之后):

exists = cnx.fetchone()

或者只是

print cnx.fetchone()

【讨论】:

    【解决方案2】:

    存在许多变体,但最简单的是:

    select count(*) > 0 from ref_locations where "Port"='ORAN'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 2019-03-14
      • 2018-06-03
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      相关资源
      最近更新 更多