【问题标题】:Python: Error Importing data from CSV to Postgres (ERROR: invalid input syntax for integer:)Python:将数据从 CSV 导入 Postgres 时出错(错误:整数的输入语法无效:)
【发布时间】:2017-07-03 14:12:36
【问题描述】:

我编写了一段 Python 代码,它应该将 CSV 数据复制到我创建的用于托管数据的表中。代码如下:

def sql_copy_command(csv_file, schema, database, table, delimiter = ',', header = True):
    if header:
        sql_command = """COPY "{schema}_{tbl}"  FROM '{the_csv_file}'  DELIMITER '{dlm}' CSV HEADER;""".format(the_csv_file = csv_file, db = database, tbl = table, dlm = delimiter, schema = schema)

    else:
        sql_command = """COPY "{schema}_{tbl}"  FROM '{the_csv_file}' DELIMITER '{dlm}' CSV;""".format(the_csv_file = csv_file, db = database, tbl = table, dlm = delimiter, schema = schema)

    return sql_command

这会引发以下错误:

DataError: invalid input syntax for integer: "Visa"
CONTEXT:  COPY insight_transaction, line 2, column id: "Visa"

在我看来,postgres 希望看到的不是 account_type,它是我模型中的第一个字段,而是 ID,它是表中的第一列。鉴于 ID 是自动生成的,我不知道如何在我的代码中解决这个问题。

【问题讨论】:

    标签: python postgresql python-3.x csv


    【解决方案1】:

    指定要复制到的列:

    copy my_schema.my_table (account_type, col5, col2) from 'the_csv_file' csv
    

    https://www.postgresql.org/docs/current/static/sql-copy.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-12
      • 2014-07-17
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 2012-06-29
      • 2020-04-27
      • 1970-01-01
      相关资源
      最近更新 更多