I am trying to insert some rows into a table which开发者_运维技巧 has a field of integers, which can be NULL:
cur.execute("INSERT INTO mytable (id, priority) VALUES (%(id)d, %(priority)d)", \
{'id': id, 'priority': priority})
The priority variable is either an integer or None
. This works when priority has an integer value, however, when it is None
I get the following error:
internal error in 'BEGIN': int argument required
I notice that for string formatting for Python in general you cannot use None
as the value of an integer to be formatted - it throws the same error that pgdb is throwing. However, when I change the formatting string to %(priority)s
the error changes to:
internal error in 'BEGIN': unsupported format character 'W' (0x57) at index 60
I guess that's because I'm then trying to import a string into an integer field.
How do I import the NULL values?
Normally Postgresql performs automatic casting of string values to integer for integer columns. So it is generally safe to use a string formatter like %(priority)s for an integer column provided the string parameter contains an integer or is None. If the string is set to None then the column will be assigned NULL.
精彩评论