简体   繁体   English

使用问号在sqlite3中进行参数化查询

[英]Parameterized queries in sqlite3 using question marks

I am using sqlite3 module with Python and have this code so far. 我正在将sqlite3模块与Python配合使用,到目前为止已经有了这段代码。 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] . 该代码应该在寻找datetime等于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])

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 : //docs.python.org/2/library/sqlite3.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM