0

我正在尝试使用 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 的第 4 个字符串 %s 或 Null(取决于数组是否包含“None”)。

但是当我尝试将 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

有谁知道为什么会这样?

4

1 回答 1

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)])
于 2017-03-01T12:34:02.260 回答