简体   繁体   中英

Not able to insert multiple columns in once using executemany

I have two variables to insert in my table.

  • user_id - int
  • marks - float

and I am having this data for multiple users like this:

user_ids = (-,-,-,-,-,-,-)  **TUPLE**
marks = (-,-,-,-,-,-,-,-)    **TUPLE**

I want to insert this data into my table using executemany and I am executing this query in my flask snippet:

con = pymysql.connect(
    host=host,
    user=user,
    password=password,
    db=db,
    charset=charset,
    cursorclass=pymysql.cursors.DictCursor,
    port=port,
)
cur = con.cursor()
percs = calcattnonull()

# percs contains list of dictionaries.
# {[<'user_id'>: <'marks'>], [<'user_id'>: <'marks'>]........}
id_ = []
perc_ = []
final = []
for perc in tqdm(percs):
    id_.append(perc["user_id"])
    perc_.append(perc["att_perc"])

id_ = tuple(id_)
perc_ = tuple(perc_)
final.append(id_)
final.append(perc_)
cur.executemany(
    "UPDATE dream_offline_calculate SET (user_id,att_percentage) VALUES (?,?)",
    final,
)
con.commit()

I am getting this error again and again: TypeError: not all arguments converted during string formatting

Thanks in advance for helping me.

executemany takes an iterable of the same placeholders you would use when calling execute several times.

So if your original query would be

cur.execute(
  "UPDATE dream_offline_calculate SET (user_id,att_percentage) VALUES (?,?)",
  (user_id, att_perc),
)

the equivalent executemany would be

cur.executemany(
  "UPDATE dream_offline_calculate SET (user_id,att_percentage) VALUES (?,?)",
  [(user_id, att_perc)],
)

So that said, simply

cur.executemany(
    "UPDATE dream_offline_calculate SET (user_id,att_percentage) VALUES (?,?)",
    [(perc["user_id"], perc["att_perc"]) for perc in percs],
)

should do the trick.

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