Parameterized queries in sqlite3 using question marks

牧云@^-^@ 提交于 2019-12-12 06:26:35

问题


I am using sqlite3 module with Python and have this code so far. In the database I have stored daily weather conditions, and now I need my code to replace some rows with updated data. The code is supposed to be looking for the row with datetime value equal to new_data[0].

The way I parameterized the query is wrong, but cannot figure out the correct and most elegant way of going about it!

new_data = ['12 Mar 2014', 'sunny', 20, 12]

conn = sqlite3.connect(database_file)
c = conn.cursor()
c.execute("UPDATE weather SET datetime = ?, condition = ?, high = ?, low = ? WHERE datetime = %s" new_data, %new_data[0])

回答1:


You are mixin up a parameterized query with string operations. First, that's highly insecure and second, you have created a problem with your syntax (you missed a comma after your query string). Try this instead:

new_data = ('12 Mar 2014', 'sunny', 20, 12, '12 Mar 2014',)

conn = sqlite3.connect(database_file)
c = conn.cursor()
c.execute("UPDATE weather SET datetime = ?, condition = ?, high = ?, low = ? WHERE datetime = ?", new_data)

More details can be found here: https://docs.python.org/2/library/sqlite3.html



来源:https://stackoverflow.com/questions/22776756/parameterized-queries-in-sqlite3-using-question-marks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!