简体   繁体   中英

How do I use WHERE after inserting variables in sqlite3

I want to update a specific row using its OID. I don't how to use UPDATE in a way that it grabs the variable updatednumber to UPDATE only the specific row I want.

import sqlite3

conn = sqlite3.connect('test.db')
c = conn.cursor()

test = 12

def subtract():
    query = ("SELECT * FROM test WHERE oid = 2") 
    c.execute(query)
    record = c.fetchone()
    r = record[1]
    updatednumber = (test - r)



def subtract1():
    c.execute("""UPDATE products SET qty = (:paid),
              {
              
              'tpaid': updatednumber
              
              }
              WHERE oid = 2""")

subtract()
subtract1()

When I run this, it tells me that { is an unrecognized token.

This syntax is wrong:

c.execute("""UPDATE products SET qty = (:paid),
          {
           
          'tpaid': updatednumber
              
          }
          WHERE oid = 2""")

since you've embedded the dictionary inside the query string; it should be the second parameter to execute() . So do this instead:

c.execute("UPDATE products SET qty = :paid WHERE oid = :oid", {'paid': updatednumber, 'oid': 2})

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