To log error lines while inserting data into the postgres table from a text file using python
I am new to python and postgres. I have a code which reads from a csv file and inserts the data into a table. The code only works when there are error free lines in the file. But if there are any errors in some of the lines I want python to ignore those lines and insert the rest of the lines into the table. The lines with the error should be written into a separate file. The code is as below:
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')" 开发者_StackOverflow社区% (tuple(row))
cur.execute(statement)
conn.commit()
if you detect errors with an exception raised, try this :
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
精彩评论