使用NULLIF与Psycopg2类型错误

时间:2017-03-01 12:20:54

标签: python postgresql types psycopg2 nullif

我尝试使用NULLIF函数通过psycopg2过滤INSERT INTO命令中的一些空条目。

如果列需要数字,问题是它不会起作用,因为NULLIF函数似乎被解释为文本。

我的表包含5列:

cursor.execute(CREATE TABLE myDb.myTable (id serial PRIMARY KEY, name varchar, value_min decimal, value_max decimal, action_name varchar, nb_solutions integer);")

我使用以下命令从字符串数组中插入一些数据:

cursor.executemany("INSERT INTO myDb.myTable (name, value_min, value_max, action_name, nb_solutions) VALUES (%s, %s, %s, NULLIF(%s,'None'), %s)", myArray[1:len(myArray)])

在这种情况下,NULLIF被正确处理并从myArray或Null插入第四个字符串%s(取决于数组是否包含'无')。

但是当我尝试将NULLIF应用于第5列(整数)时,NULLIF突然被解释为文本:

cursor.executemany("INSERT INTO myDb.myTable (name, value_min, value_max, action_name, nb_solutions) VALUES (%s, %s, %s, %s, NULLIF(%s,'None'))", myArray[1:len(myArray)])

我收到以下错误:

ProgrammingError: column "nb_solutions" is of type integer but expression is of type text LINE 1: ...6085', ' 13.077', ' epsi', NULLIF(' 7... ^ HINT: You will need to rewrite or cast the expression. 
  args = ('column "nb_solutions" is of type integer but exp...You will need to rewrite or cast the expression.\n',) 
  cursor = <cursor object at 0x000000000578F3A8; closed: 0> 
  diag = <psycopg2.extensions.Diagnostics object> 
  pgcode = '42804' 
  pgerror = 'ERROR: column "nb_solutions" is of type integer...You will need to rewrite or cast the expression.\n' 
  with_traceback = <built-in method with_traceback of ProgrammingError object> Exported something to DB Mytable

任何人都知道为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

不要将None作为'None'字符串传递。传递真实None值,Psycopg将正确调整它。并将其转换为预期类型:

cursor.executemany('''
    INSERT INTO myDb.myTable (
        name, value_min, value_max, action_name, nb_solutions
    ) VALUES (%s, %s, %s, %s, %s::int)
''', myArray[1:len(myArray)])