简体   繁体   中英

How to update row by row using python function in sqlite3?

This question is duplicated I think, but I couldn't understand other answers...

  1. Original table looks like this.
NAME    AGE SMOKE
John    25  None
Alice   23  None
Ken     26  None
  1. I will update SMOKE column in these rows,

  2. But I need to use output of function which was coded in python check_smoke() . If I input name to check_smoke() , then it returns "Smoke" or "Not Smoke" .

  3. So final table would look like below:

NAME    AGE SMOKE
John    25  Smoke
Alice   23  Not Smoke
Ken     26  Not Smoke

I'm using sqlite3 and python3. How can I do it? Thank you for help!

You could use 1 cursor to select rows and another one to update them.

Assuming that the name of the table is smk (replace it by your actual name) and that con is an established connection to the database, you could do:

curs = con.cursor()
curs2 = con.cursor()
batch = 64            # size of a batch of records
curs.execute("SELECT DISTINCT name FROM smk")
while True:
    names = curs.fetchmany(batch)                             # extract a bunch of rows
    if len(names) == 0: break
    curs2.executemany('UPDATE smk SET smoke=? WHERE name=?',  #  and update them
              [(check_smoke(name[0]), name[0]) for name in names])
con.commit()

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