Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Sqlite UPDATE multiple values

Is there a way to do these two updates in a single instruction?

cur.execute("UPDATE table_name1 SET email = '[email protected]' WHERE id = 4")
cur.execute("UPDATE table_name1 SET phone = '0400-123-456' WHERE id = 4")

I've tried all sort of variations but can't get it to work.

Edit: I want to pass email, phone and I'd as parameters.

like image 715
Axle Max Avatar asked Apr 02 '17 22:04

Axle Max


2 Answers

You're solution opens you up to SQL injections. If you read the first section of the documentation, it specifically says not to do it the way you are proposing:

Never do this -- insecure!

symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

Do this instead

t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)

So you should change your code to something along the following lines:

conn = sqlite3.connect('connex.db')
cur = conn.cursor()
mobileval = '0400-123-456'
emailval = '[email protected]'
constrain = 4

q = "UPDATE licontacts310317 SET (?, ?) 
             WHERE (?)=(?)"

cur.execute(q, (liemailval, limobileval, id, constrain) )

conn.commit()
conn.close()

I haven't tested it, but hopefully you get the idea =)

like image 54
ron_g Avatar answered Nov 14 '22 21:11

ron_g


The following works: Its just standard SQL at this point.

cur.execute("""UPDATE table_name1
            SET email = '[email protected]', phone = '0400-123-456'
            WHERE id = 4""")
like image 21
David Avatar answered Nov 14 '22 22:11

David