简体   繁体   English

python sql,“选择? 从表在哪里? 像?”,(选择,在哪里,像)

[英]python sql, “select ? from table where ? like ?”,(selected,where,like))

    select=input("select: ")
    for row in data.execute('select ? from stocks where date like "2015-11-05" ',(select)):

        print(row)

This is is all I'm trying to do right now but I'm getting this error and can't find a solution 这就是我现在要尝试的全部操作,但是出现此错误并且找不到解决方案

    sqlite3.ProgrammingError: Incorrect number of bindings supplied. 
    The current statement uses 1, and there are 5 supplied.

Is there a way to do this? 有没有办法做到这一点? I'm assuming the answer will be similar to the title. 我假设答案将类似于标题。

(select) is not a tuple and is a string, a string of 5 characters in your case. (select)不是元组,而是一个字符串,在您的情况下为5个字符的字符串。 Since strings are also iterables, sqlite splits your string into characters and tries to parameterize the query with all of the 5 characters in the string. 由于字符串也是可迭代的,因此sqlite将字符串拆分为字符,并尝试使用字符串中的所有5个字符对查询进行参数化。 Instead you meant to have a tuple with a single element inside: 相反,您的意思是要在其中包含一个具有单个元素的元组:

data.execute('select ? from stocks where date like "2015-11-05" ', (select, ))

But, the problem is - this is not going to work, you cannot parameterize the table or column names and you are forced to use string formatting: 但是,问题是-这是行不通的,您无法参数化表或列的名称,而您不得不使用字符串格式:

data.execute('select {} from stocks where date like "2015-11-05"'.format(select))

Note that, since we are using string formatting here, we are making the code vulnerable to SQL injections - you should definitely validate the select variable value and protect yourself against SQL injections (not sure who would be the user of the program in your case though). 请注意,由于我们在这里使用字符串格式,因此使代码容易受到SQL注入的侵害-您绝对应该验证select变量值并保护自己免受SQL注入的影响(尽管不确定在您的情况下谁将成为程序的用户) )。

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

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