首页 > 解决方案 > 无法将 csv 文件加载到 heroku 中的 postgres 表中 - 错误:整数类型的输入语法无效:

问题描述

Error in copying db  invalid input syntax for type integer: "0"
CONTEXT:  COPY spellbeeword_tb, line 1, column id: "0"  

我的代码:

import os
import psycopg2

def writedb(conn):
    cur = conn.cursor()
    print("Started opening file to copy into table")

    try:
        with  open("spellbee/docs/Spell_Bee_Word_db.csv", 'r', encoding="utf-8") as f:
            sql_copy= "COPY spellbeeword_tb  FROM stdin (FORMAT CSV)"
            cur.copy_expert(sql=sql_copy,file=f)
            print('successfully copied files into db')
            # commit changes
            conn.commit()
            print("Committed changes")
    
    except Exception as error:
        print('Error in copying db ',error)
    finally:
        if conn:
            conn.close()
            f.close()

def main():

    DATABASE_URL = os.environ['DATABASE_URL']

    

    try:
        conn = psycopg2.connect(DATABASE_URL, sslmode='require')
        
        
        writedb(conn)

    except(Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn:
            conn.close()

if __name__ == "__main__" :
    main()


    operations = [
            migrations.CreateModel(
                name='BeeWord',
                fields=[
                    ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                    ('level', models.CharField(max_length=10)),
                    ('word', models.CharField(max_length=90)),
                ],
 

operations = [
    migrations.AlterModelTable(
        name='beeword',
        table='spellbeeword_tb',
    ),
> 0 ONE gel
> 1 ONE day
> 2 ONE scorch

它在上面的示例 csv 数据上引发错误。
它不接受 csv 给出的整数值,我尝试给出最后两列,不包括 csv 中的索引。两种方式都不接受。请提供解决方案。
CSV 文件只包含没有标题的数据。我的 ORM 看起来像上面。

标签: pythoncsvdjango-modelssqlbulkcopyheroku-postgres

解决方案


COPY 命令生成一个标题行,导入命令将其作为数据读取。

告诉导入命令不要读取第一行。

为了避免生成标题行,我不知道如何默认省略

要忽略标题行,请在导入命令中插入 HEADER 选项,并在 csv 文件中插入标题。现在它工作正常

try:
        with  open("spellbee/docs/Spell_Bee_Word_db.csv", 'r', encoding="utf-8") as f:
            #cur.copy_from(f,'spellbeeword_tb', sep=',')
            sql_copy ="COPY spellbeeword_tb  FROM STDIN WITH CSV HEADER DELIMITER ',' "
            cur.copy_expert(sql=sql_copy,file=f)
            print('successfully copied files into db')
            # commit changes
            conn.commit()
            print("Committed changes")
    
    except Exception as error:
        print('Error in copying db ',error)
    finally:
        if conn:
            conn.close()
            print("Finally connection closed")
            f.close()

推荐阅读