سؤال

How do I use string substitution in Psycopg2 to handle both NULL and non-NULL values?

For example:

sql = 'SELECT * FROM table WHERE col = %s;'
possible_params = [1, None]

for x in possible_params:
    print cur.mogrify(sql,(x,))

I need the first query to look like SELECT * FROM table WHERE col = 1; And the second to be the functional equivalent of SELECT * FROM table WHERE col IS NULL;

Is there a trick? I have many columns that may be NULL or have a value so building the SQL dynamically is fairly cumbersome.

هل كانت مفيدة؟

المحلول

Every time you don't know if a parameter will be NULL you can use the following pattern:

SELECT * FROM table WHERE col = <parameter> OR (col IS NULL AND <parameter> IS NULL)

where <parameter> is your parameter.

But note that I am using the same parameter two times in a row, so you need to switch to the the dict format. The full code is:

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,))

نصائح أخرى

I tried everything I could think of:

SELECT COUNT(*) FROM table WHERE col = Null;
SELECT COUNT(*) FROM table WHERE col::TEXT = '';
SELECT COUNT(*) FROM table WHERE col IN (Null::TEXT);
SELECT COUNT(*) FROM table WHERE col IN (VALUES (NULL::TEXT));

and then just mashed kludgy if statements, e.g.:

if record['api'] is not None:
    sql += 'api = %(api)s'
else:
    sql += 'api IS NULL'
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top