Dyl*_*ger 6 python postgresql psycopg2 postgresql-9.2
如何在Psycopg2中使用字符串替换来处理NULL和非NULL值?
例如:
sql = 'SELECT * FROM table WHERE col = %s;'
possible_params = [1, None]
for x in possible_params:
print cur.mogrify(sql,(x,))
Run Code Online (Sandbox Code Playgroud)
我需要第一个查询看起来像SELECT * FROM table WHERE col = 1;
第二个是功能相当于SELECT * FROM table WHERE col IS NULL;
有诀窍吗?我有很多列可能是NULL或有一个值,因此动态构建SQL是相当麻烦的.
每次您不知道参数是否为NULL
您可以使用以下模式:
SELECT * FROM table WHERE col = <parameter> OR (col IS NULL AND <parameter> IS NULL)
Run Code Online (Sandbox Code Playgroud)
你的参数在哪里<parameter>
。
但请注意,我连续两次使用相同的参数,因此您需要切换到格式dict
。完整代码是:
sql = 'SELECT * FROM table WHERE col = %(p)s OR (col IS NULL AND %(p)s IS NULL)'
possible_params = [{"p":1}, {"p":None}]
for x in possible_params:
print cur.mogrify(sql,(x,))
Run Code Online (Sandbox Code Playgroud)