简体   繁体   English

将值传递给Sqlite3 python

[英]Passing a value into Sqlite3 python

I am trying to pass a method parameter into an sqlite command and I am having problems. 我试图将方法参数传递给sqlite命令,但出现问题。

I have tried several different methods including: 我尝试了几种不同的方法,包括:

c.execute('''SELECT ?, count(*)
             FROM posts
             GROUP BY 1''', (var,))

c.execute('''SELECT :variable, count(*)
             FROM posts
             GROUP BY 1''', {"variable" : var})

I have looked at the python docs on this and believe I am following them. 我已经看过有关此的python文档 ,并相信我正在关注它们。

Both these methods don't select the columns, but return 这两种方法都不选择列,而是返回

[('lang', 3284469)]

Where lang is the name of the column and the value of the variable being passed. 其中lang是列名和要传递的变量的值。 It should look more like 它看起来应该更像

[('en', 3289)]
[('es', 845)]
....
[('ze', 39)]

The only method I have been able to get working is: 我能够上班的唯一方法是:

c.execute('''SELECT '''+var+''', count(*)
             FROM posts
             GROUP BY 1''')

I am not particularly happy with this, is there a better way to do this? 我对此并不特别满意,是否有更好的方法来做到这一点? What am I doing wrong? 我究竟做错了什么? Thanks 谢谢

That is not the way parameterized requests work. 这不是参数化请求的工作方式。 You should only use parameters for values , not for identifiers. 您仅应将参数用于 ,而不用于标识符。 That means that request parameters should not be column names, nor table names, and occur only in the where or having clause. 这意味着请求参数不应是列名或表名,而应仅出现在where或hading子句中。

So if you want the column name or the table name to be variable, you must dynamically build the request string, and when you want values in the where clause to be dynamic, you use parameters: 因此,如果您希望列名或表名是变量,则必须动态构建请求字符串,并且当您希望where子句中的值是动态的时,可以使用参数:

c.execute('''SELECT '''+var+''', count(*) as total
             FROM posts
             GROUP BY 1
             HAVING total > ?''', (minval,))

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

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