如何在plpython查询中检查值是否返回?

2024-06-10 06:16:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在PostgreSQL函数的plpythonu中有此赋值:

result=plpy.execute("select  value from table  where doctitle like '%%%s%%'"%projectname)
if result:
    final = result[0]["value"]

查询可以返回1个文本结果,也可以不返回任何结果。在

问题是如果查询没有返回任何结果,if result:条件仍然是true(因为它包含value列)。。。我希望只有在value列中有实际值时,final的赋值才会发生。我该怎么检查?在


Tags: 函数fromexecuteifvaluepostgresqltableresult
1条回答
网友
1楼 · 发布于 2024-06-10 06:16:47

结果对象模拟列表或字典对象。检查其长度:

if len(result) > 0:

但是您的测试应该是空列表,或者字典的计算结果是False

^{pr2}$

返回false

select p();
 p 
 -
 f

将参数传递给execute,而不是替换您自己。否则,您将容易受到SQL注入的攻击:

query = """
    select value
    from table
    where doctitle like format('%%%s%%', $1)
"""
plan = plpy.prepare(query, ["text"])
result = plpy.execute(plan, [_text_parameter])
if result:
    final = result[0]["value"]

https://www.postgresql.org/docs/current/static/plpython-database.html

相关问题 更多 >