问题描述
||
我是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