vendredi 22 avril 2016

Python: Using an SQL query and a nested for loop to read and reinsert data into a database?

A bit of clarity: I've only used python for two weeks as of now. I have a assignment at work to produce a script that will read a database, perform some calculations then update the database with the calculated values.

I know how to perform an SQL query using sqlite3 and i know how to update a table.

Currently I'm using something like:

c.execute("SELECT x,y,z FROM {tn} "\
    .format(tn=Table1, x=column1, y=column2, z= column3)) 

To select the information.

I then perform the calculations, and can update the table using a single update statement per variable. So essentially it's quite innefficient.

I know that there is code to easily insert values into a table, i.e:

for t in [(1, 'Tim', 8, 'Mr.Wood'),
      (2, 'Aaron', 8, 'Mr.Henderson'),
      (2, 'Jane', 10, 'Mr.Wood'),
     ]:
c.execute('INSERT INTO Table_name VALUES (?,?,?,?)',t)

But what I'm having trouble finding is, is there a way I can incorporate that for loop and the update table? I.e. Read the values from a database (the columns aren't necessarily next to each other) then perform an update table query with a similar struture as the for loop above?

Aucun commentaire:

Enregistrer un commentaire