python-3.x - Python copy_expert 加载带有空值的数据时出现问题

标签 python-3.x postgresql psycopg2

我无法使用 copy_expert 将 csv 导入到 postgres 中的表中。错误是由于空值。

我在数据库中的字段类型是允许空值的。通过insert into手动插入证明成功

根据我目前的理解,这是因为 copy_expert 将空值转换为文本,这就是它在时间戳数据类型上失败的原因。但是,我无法找到将空值强制为空值的正确语法。下面的代码片段:

with open(ab, 'r') as f:
    cur.copy_expert("""COPY client_marketing (field1,field2,field3) FROM STDIN DELIMITER ',' CSV HEADER""", f)

错误信息:

DataError:类型时间戳的无效输入语法:“”。感谢对脚本的任何帮助或为我指出正确的来源以继续阅读。

最佳答案

我可以通过添加 force_null (column_name) 来做到这一点。例如,如果 field3 是您的时间戳:

copy client_marketing (field1, field2, field3) from stdin with (
    format csv,
    delimiter ',',
    header,
    force_null (field3)
);

希望对您有所帮助。参见 https://www.postgresql.org/docs/10/sql-copy.html

关于python-3.x - Python copy_expert 加载带有空值的数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56624261/

相关文章:

python - 在保持类型的特定类型 REST 端点上执行通用函数

当进程数和工作线程数增加时,Python 多处理池 API 无法有效工作

python - 数据帧合并给出 `Process finished with exit code 137 (interrupted by signal 9: SIGKILL)`

django - 使用内置全文搜索的 django postgres 通过特定列进行全文搜索

python - Psycopg2 使用 pip 安装有效但无法在 OS X 10.9 上导入模块

python:按名称分配属性值

python - Tornado +桃子。不断增长的响应时间

postgresql - 带有可序列化隔离的 PostgreSQL 9.2.1 中的谓词锁定

django - 在Django的ORM中,有没有办法检测代码是否在事务内执行?

python - 使用 psycopg3 在服务器之间复制表