[Tutor] help with postgreSQL and .csv

Ismar Sehic i.sheeha at gmail.com
Mon Sep 2 23:22:00 CEST 2013


hello.
i wrote the following code, to insert some values from a csv file to my
postgres table :

*    ******
*import psycopg2*
*conn = psycopg2.connect("host = ***.***.***.*** user=******* dbname =
****** ")*
*cur = conn.cursor()*
*import csv*
*with open('HotelImages.csv', 'rb') as f:           *
*    mycsv = csv.reader(f, delimiter = '|')*
*    for row in mycsv:*
*        hotel_code = row[0]*
*        hotel_url = row[-1]*
*        sql  = " UPDATE hotel SET path_picture = "+"';"+hotel_url+"'
 WHERE code LIKE '"+"%"+hotel_code+"'"*
*        print '--->'+sql*
*        cur.execute(sql)*
*        conn.commit()*
*c.close()*
*print '----->Complete'*
*    *******


the for loop iterates through the table, comparing the values from the csv
line by line with the table column 'code'.
example of csv lines:
*    ******
*94176|HAB|7|2|09/094176/094176a_hb_w_007.jpg*
*94176|HAB|8|3|09/094176/094176a_hb_w_008.jpg*
*94176|BAR|6|7|09/094176/094176a_hb_ba_006.jpg*
*94176|RES|5|6|09/094176/094176a_hb_r_005.jpg*
*94176|HAB|1|1|09/094176/094176a_hb_w_001.jpg*
*94176|CON|4|8|09/094176/094176a_hb_k_004.jpg*
*94176|COM|2|4|09/094176/094176a_hb_l_002.jpg*
*94176|RES|3|5|09/094176/094176a_hb_r_003.jpg*
*    ******
example of the code column value : *GEN94176, XLK94176,KJK94176*....
the number before the first ' | ' gets just one hit in the database table
column, inserts some random picture once.also, if the same numbers in some
other 'code' column row are appearing, but in different order, it inserts
the same picture.
my goal is to make it write all the picture url values separated by a ';'
in just one field and to input the data correctly.
i'm new to python, as a matter of fact, just started to learn programming.
i would really like to know where is my mistake.advice and help appreciated!

Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130902/a571b765/attachment.html>


More information about the Tutor mailing list