Python PostgreSQL using copy_from to COPY list of objects to table -
i'm using python 2.7
, psycopg2
connect db server ( postgresql 9.3 ) , list of objects of ( product class ) holds items want insert
products_list = [] products_list.append(product1) products_list.append(product2)
and want use copy_from
insert products list product table. tried tutorials , had problem converting products list csv format because values contain single quote, new lines, tabs , double quotes. example ( product description ) :
<div class="product_desc"> details : product's name : name </div>
the escaping corrupted html code adding single quote before single quote , it, need use save way convert list csv copy it? or using other way insert list without converting csv format??
i figured out, first of created function convert object csv row
import csv @staticmethod def adding_product_to_csv(item, out): writer = csv.writer(out, quoting=csv.quote_minimal,quotechar='"',delimiter=',',lineterminator="\r\n") writer.writerow([item.name,item.description])
then in code created csv file using python io
store data in copy
, stored every object in csv file using previous function:
file_name = "/tmp/file.csv" myfile = open(file_name, 'a') item in object_items: adding_product_to_csv(item, myfile)
now created csv
file , it's ready copied using copy_from
exists in psycopg2
:
# reason needs closed before copying table csv_file.close() cursor.copy_expert("copy products(name, description) stdin delimiter ',' csv quote '\"' escape '\"' null 'null' ",open(file_name)) conn.commit() # clearing file open(file_name, 'w').close()
and it's working now.
Comments
Post a Comment