Python3动态sqlite选择查询

2024-09-30 22:14:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力复制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查询的输出

如何使用动态查询,使用变量名选择行


Tags: 方法fromidexecutesqlitedewhereselect
3条回答

您需要将字符串格式化参数替换结合起来,以创建可以安全执行的查询

# Sqlite uses question marks for value placeholders
# and double-quotes for identifiers.  See
# https://www.sqlite.org/lang_keywords.html

sql = 'SELECT "%s" FROM balances WHERE id = ?'
# Use string formatting (%, .format, f-string) to add the column name(s)
sql = sql % column_name
# Use parameter substitution to add the value(s) to ensure correct quoting of values
result = cursor.execute(sql, (1,))

值占位符有一种替代形式

sql = 'SELECT "%s" FROM balances WHERE id = :id'
sql = sql % column_name
result = cursor.execute(sql, {'id': 1})

按如下方式定义查询:

query = f'''SELECT {elementName} FROM {tableName} WHERE id={userId}'''

然后:

cursor.execute(query)

应在构造查询之前指定参数

请注意,python2中不支持这种格式

下面的答案同样有效,我能够让它与cursor.execute("SELECT (" + elementName + ") FROM balances WHERE id=?", (userId))一起工作。我发现的另一个问题是,有些elementName条目中有一个连字符,我认为脚本不喜欢。我从数据库中删除了所有的hypens并使其正常工作,感谢所有人的及时回复

相关问题 更多 >