简体   繁体   中英

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 inefficient.

I know that there is code to easily insert values into a table, ie:

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? Ie Read the values from a database (the columns aren't necessarily next to each other) then perform an update table query with a similar structure as the for loop above?

EDIT:

I am using dictionaries as a replacement for a switch/case statement. I have the cases defined as functions and the switch function with the 'cases' defined.

For each case I will have different information to take from the database, and different calculations to perform. I can do this, and at the moment, I am using two-four UPDATE statements per function to update the database with the new calculated values. My question is: Is it possible to update a table with more than one value at one time using only one statement?

like this:

c.execute("UPDATE table SET 'value' WHERE columnName = {cn}
                        SET 'value' WHERE ColumnName2 = {cn2}
                        ...
                       ")

I'm not sure I fully understand, but I'll try to help you.

After you read the data from the DB, for each line of data, you perform a calculation and INSERT the data to the DB. Correct? If so, you should create a function, like so:

def update_db_based_on(some_info):
    calculated_data = some_calculation(some_info) 
    insert_to_db(calculated_data) 

Then, you could go like so:

for line in data_from_db:
    update_db_based_on(line) 

Is that what you meant?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM