python - 如何将 Null 作为值传递给存储过程以使用 python 查询 postgresdb?

标签 python python-3.x postgresql dictionary

我有一个存储过程,我需要将“null”作为值传递给查询

这是字典:

dict1 = {'name':'apple', 'age':23, 'place':None, 'year':None, 'country': ''}

注意:相应键的值将始终更改。

我尝试了这个,但它不适用于我的场景,因为他/她有常量值并且没有像我一样的空字符串。 How to insert 'NULL' values into PostgreSQL database using Python?

我试图将值作为 None 传递给 null,但 python 将其作为 None 而不是 null。它向我抛出一个错误,提示 psycopg2.ProgrammingError: column "none"does not exist

如何使用 python 将 dict1 None 值作为空值传递给存储过程查询,如下所示?

select * from sampletable."getvalues"('apple', 23, null, null, '')

最佳答案

Nonepsycopg2 正确转换为NULL,无论查询中是否有函数。这是将字典传递给 cursor.execute() 的正确方法:

dict1 = {'name':'apple', 'age':23, 'place':None, 'year':None, 'country': ''}
query = cur.mogrify('select * from func(%(name)s, %(age)s, %(place)s, %(year)s, %(country)s)', dict1)
print(query)

输出:

b"select * from func('apple', 23, NULL, NULL, '')"

关于python - 如何将 Null 作为值传递给存储过程以使用 python 查询 postgresdb?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52820131/

相关文章:

python - 如何处理和设置错误,返回并在python中返回值?

python - R:与 numpy 的 .dtype.itemsize 和 .dtype.alignment 数组属性等效的 R 是什么?

python - 如何使用 BeautifulSoup 查找没有 id 或类名的 html 标签?

xml - 如何在 Postgresql 中查询 XML 列?

python - 逆加权分布

python - 格式 () : ValueError: Precision not allowed in integer format specifier

python - 如何在 Python 中检索 UTC 时间?

sql - 如何使用MATLAB和JDBC加快表检索的速度?

postgresql - 无法将 varchar(255) 转换为 float

python - Reportlab 在表格中插入水平线