0

I am trying to write an update query but I could not manage the string. My connections is ok. My query is like this:

str='hello'
cursor.execute('UPDATE users SET message = '+str+' WHERE UserId=13')

This is giving me error: undefined column name 'hello'. I want to update message column as hello but it is getting it as a column name. In sql, when I write it as UPDATE users SET message = 'hello' WHERE UserId=13 it works but I could not figured out how should I write my query like that in python. How should I write my query?

aoiTenshi
  • 547
  • 1
  • 6
  • 20
  • 4
    *Don't* concatenate strings to generate queries. What if `str` contained `3; DROP TABLE USERS; --` ? That's how SQL injection attacks happen. If you check the `cursor.execute` docs you'll see how to pass query parameters – Panagiotis Kanavos Jun 30 '22 at 08:20
  • Your Python script creates the following string: `UPDATE users SET message = hello WHERE UserId=13`, you need to quote `str` within the SQL statement. – Maurice Meyer Jun 30 '22 at 08:21
  • 1
    [Bobby Tables](https://xkcd.com/327/) is back. – Matthias Jun 30 '22 at 08:25

2 Answers2

1

try it:

cursor.execute('UPDATE users SET message="{}" WHERE UserId=13'.format("hello"))
maya
  • 1,029
  • 1
  • 2
  • 7
0

try this:

str='hello'
cursor.execute("UPDATE users SET message = '" + str + "' WHERE UserId=13")
Majed Jaber
  • 197
  • 1
  • 7