我正在努力复制sqlite SELECT查询
sqlite> select "de-515" from balances where id = '1';
de-515
0.1
sqlite>
sqlite没有任何问题,但是当我尝试将此查询构建到python脚本中时,我所做的一切似乎都不起作用。我尝试了以下方法,目的是将python变量设置为上面看到的0.1
值
elementBalQuery = 'SELECT "%s" FROM balances WHERE id="%s"'
cursor.execute(elementBalQuery, (elementName,userId))
curBal = cursor.fetchall()
print("curBal = ", curBal)
这导致
Traceback (most recent call last):
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 2 supplied.
这也是失败的
cursor.execute("SELECT %s FROM balances WHERE id=?", % (elementName), (userId))
cursor.execute("SELECT %s FROM balances WHERE id=?", % (elementName), (userId))
SyntaxError: invalid syntax
我尝试了其他几种方法来构建这个查询,但无法找出我遗漏了什么。我来自bash的背景,在那里我可以轻松地将var设置为等于sqlite查询的输出
如何使用动态查询,使用变量名选择行
您需要将字符串格式化和参数替换结合起来,以创建可以安全执行的查询
值占位符有一种替代形式
按如下方式定义查询:
然后:
应在构造查询之前指定参数
请注意,python2中不支持这种格式
下面的答案同样有效,我能够让它与
cursor.execute("SELECT (" + elementName + ") FROM balances WHERE id=?", (userId))
一起工作。我发现的另一个问题是,有些elementName条目中有一个连字符,我认为脚本不喜欢。我从数据库中删除了所有的hypens并使其正常工作,感谢所有人的及时回复相关问题 更多 >
编程相关推荐