简体   繁体   English

Python选择存在带有变量的SQLite3

[英]Python select exists SQLite3 with variable

I am to be unable to get the following code to work. 我将无法使以下代码正常工作。 I know how to use python variables in queries, but somehow I can't get this right. 我知道如何在查询中使用python变量,但是不知何故我做不到这一点。 The query works fine when I hard code the 'icaocode' variable in the query, but not if I try to use a variable. 当我在查询中对'icaocode'变量进行硬编码时,该查询工作正常,但是如果我尝试使用一个变量,则该查询无法正常工作。 What is wrong with this code? 此代码有什么问题?

icaocode = input()

c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO = ?)", (icaocode))
if c.fetchone():
    print("Found!")
else:
    print("Not found...")

Received error: 收到错误:

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

In Python, wrapping an expression in parentheses does not make any difference, (icaocode) is exactly the same as icaocode . 在Python中,将表达式用括号括起来没有任何区别, (icaocode)icaocode

The execute method expects some kind of list of parameters, so it sees the string as a sequence of four characters. execute方法需要某种类型的参数列表 ,因此它将字符串视为四个字符的序列。

To tell Python that you want a tuple with a single element, you have to add a comma: 要告诉Python您想要一个具有单个元素的元组,必须添加一个逗号:

c.execute("... WHERE ICAO = ?", (icaocode,))

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

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