[Tutor] My Name is John and I copy and paste

Kent Johnson kent37 at tds.net
Tue Apr 18 13:32:56 CEST 2006


John CORRY wrote:

> Thanks for all the help so far on my database questions.  I have now 
> developed a program that reads in info from a csv file and updates 
> already existing records in my database.  I have enclosed the code 
> below.  The good news is that it is working.  However, I used copy and 
> paste and amended the text to write the code and it seems rather 
> longwinded.  Is there a quicker/better way to write the code below?

Hi John,

What you need here is a loop. Have you learned about for loops? Here is 
a short example to get you started. Any Python tutorial will tell you more.

In [1]: rows = [ ['row1', 0], ['row2', 55], ['row3', 23] ]

In [2]: for row in rows:
    ...:     print row[0], row[1]
    ...:
    ...:
row1 0
row2 55
row3 23

Kent

> path = "c:/test/import.csv"
> 
> import mx.ODBC
> 
> import mx.ODBC.Windows
> 
> import csv
> 
> reader = csv.reader(open(path,"rb"))
> 
> for row in reader:
> 
>     db = mx.ODBC.Windows.DriverConnect('DSN=vfp')
> 
>     c = db.cursor()
> 
>     c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = ? 
> and finish_dro = ?', ( float(row[3]), row[0], float(row[2])))
> 
>     c.execute('UPDATE cost_grid SET rrp_1 = ? where cost_grid_id = ? and 
> finish_dro = ?', ( float(row[4]), row[0], float(row[2])))



More information about the Tutor mailing list