在使用python从文本文件将数据插入到postgres表中的同时记录错误行

问题描述

|| 我是python和postgres的新手。 我有一个从csv文件读取并将代码插入表中的代码。 该代码仅在文件中有无错误行时才有效。 但是如果某些行中有任何错误,我希望python忽略这些行并将其余的行插入表中。带有错误的行应写入单独的文件中。 代码如下:
import psycopg2
import csv

try:
    conn = psycopg2.connect(\"dbname=\'postgres\' user=\'postgres\' host=\'localhost\' 
    password=\'postgres\'\")
except:
    print \"I am unable to connect to the database\"

cur = conn.cursor()

filehandle = open(\'abc.csv\',\'r\') 
reader = csv.reader(filehandle,delimiter=\',\')

for row in reader:
    statement = \"INSERT INTO abc(col1,col2,col3) VALUES (\'%s\',\'%s\',\'%s\')\" % (tuple(row))
    cur.execute(statement)

conn.commit() 
    

解决方法

        如果您发现引发异常的错误,请尝试以下操作:
for row in reader:
    try:
        statement = \"INSERT INTO abc(col1,col2,col3) VALUES (\'%s\',\'%s\',\'%s\')\" % (tuple(row))
        cur.execute(statement)
    except:
        #do the stuff in case of error
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...