问题
执行以下程序报错:sqlite3.OperationalError: near “?“
sql_update = 'update images set ? = ? where id = ?'
args = (k, inputs[k], update_id, )
cur.execute(sql_update, args)
其中,args = ('name', 'robin', 2)
不怎么看,怎么改,SQL 语句都没有问题,但是不论怎么做都会报错!浪费半天时间。
探索
在 pyqt 中执行 sqlite 的 SQL 语句报错
db_name = 'images'
sql_search = "select * from ? where id=?"
args = (db_name, int(search_id))
cur.execute(sql_search, args)
在执行上面代码时出现报错:sqlite3.OperationalError: near "?": syntax error
百思不得其解,一度怀疑是 sqlite 传递参数的方法用的不对(其实正确),直到终于执行不报错才找到问题所在:
执行下面的代码不报错:
sql_search = "select * from images where id=?"
cur.execute(sql_delete, (int(delete_id),)) # 这里int(delete_id) = 1
结果省略了表头:
xx xxx zzz ...
1 177.3 173.6 35.6 65.9 4
1 123 45 456 78 3
所以是 参数 db_name
导致了 SQL 语句报错,
对此,为了排除是参数传递个数的问题,再次执行以下代码:
sql_search = "select * from images where id=? or id=?"
args = (int(delete_id), 2) # 多加了一个参数 2
cur.execute(sql_delete, args)
执行结果并没有问题:
(结果省略了表头)
xx xxx zzz ...
1 177.3 173.6 35.6 65.9 4
2 177.3 173.6 35.6 65.9 4
3 123 45 456 78 3
4 345 65 789 45 1
现在可以确定了,所以在类似的情况中:
表的名称直接用变量值即可,不要使用变量名
被这个问题折磨了太久,对你有帮助可以点个赞!
参考:
SQLite3 传递参数的方法 | SQLite3 Methods of passing arguments
解决
答案问题的答案是:不能将SQL参数用于对象名称(例如表或列)
参考:关于python:为什么会出现错误“ sqlite3.OperationalError:在“?”附近:语法错误”?
注意:不仅表名,连列名也不能用参数代替!!!!
还有一个大坑:
sqlite
除了数字其它内容记得用引号括起来(即是是变量传参的情况也得在外面套一个引号),否则容易报错!
比如:
不然可能又是一半天的 bug
!