sql - Insert into table with type casting and condition in INSERT statement
问题描述
Based on this previous question
I am trying to compose an insert statement in Python using psycopg2 with some data. The query works beautifully in postgresql console but when I try it from psycopg2 I get an error.
Here's the table i want to insert to
create_test_table = """CREATE TABLE persons(
name VARCHAR,
age INT,
dob DATE,
sex VARCHAR);"""
Here's the data I want to insert
d_ = {"name":"Gino", "age": "", "dob": "na", "sex": "M"}
And here's my query:
cur.execute("""INSERT INTO persons (age,dob,sex,name)
VALUES (CASE WHEN cast(%(age)s as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE %(age)s END,
CASE WHEN cast(%(dob)s as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE %(dob)s END,
CASE WHEN cast(%(sex)s as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE %(sex)s END,
CASE WHEN cast(%(name)s as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE %(name)s END)""", d_)
Error message:
----> 5 CASE WHEN cast(%(name)s as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE %(name)s END)""", d_)
ProgrammingError: column "age" is of type integer but expression is of type text
LINE 2: VALUES (CASE WHEN cast('' as text) IN ('', '#...
^
HINT: You will need to rewrite or cast the expression.
Maybe it is not possible to do this in psycopg2. Any help would be appreciated :))
解决方案
您的参数替换不正确。例如,而不是这个:
%(CASE WHEN cast(age as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE age END)s
你应该有:
(CASE WHEN cast(%(age)s as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE age END)
推荐阅读
- c++ - 成对展开可变参数模板包
- indexing - 正确存储/检索 termVector
- c# - Show() 方法不会在一秒钟前隐藏的图片框中显示 .gif
- python-3.x - 循环遍历 Pandas 中的分组列
- node.js - 在nodejs中导出的自定义模块中使用函数的问题
- entity-framework - 在实体框架中使用 lambda 语法进行多重左连接
- javascript - 打开 Google Drive Picker 时出错 - 您请求的功能当前不可用。请稍后再试
- javascript - 在 Google 表格上选择范围后,如何将所选内容粘贴到 Google 文档中?
- java - 我如何接受带有 jsoup 的 cookie?
- python - ValueError:时间数据与格式不匹配,可选毫秒