如何在对 SQLite3 的 Python 调用中获取可变长度占位符 [英] How to get variable length placeholders in a Python call to SQLite3

查看:31
本文介绍了如何在对 SQLite3 的 Python 调用中获取可变长度占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 SQL 查询中使用可变长度占位符?

Is there a way to use variable length placeholders in an SQL query?

现在用一个 3 元组,我写的东西是这样的:

Right now with a 3-tuple, I write something like this:

c.execute('SELECT * FROM table WHERE word IN (?, ?, ?)', tup)

但是如果 tup 可以有不同的长度,可能是 4 元组或 2 元组呢?在这种情况下是否有使用占位符的语法?如果不是,编写代码的首选方式是什么?

But what if the tup can be of differing lengths, perhaps a 4-tuple or 2-tuple? Is there a syntax for using placeholders in this situation? If not, what is the preferred way to write the code?

推荐答案

你必须做这样的事情(使用你的例子):

You'd have to do something like this (to use your example):

tup = ... # some sequence/tuple of unknown length
sql = 'SELECT * FROM table WHERE word IN (%s)' % ', '.join('?' for a in tup)
c.execute(sql, tup)

通过这种方式,您可以在 sqlite3 模块解析出来之前动态创建占位符列表并格式化 SQL 字符串.

This way you're dynamically creating the placeholder list and formatting the SQL string before the sqlite3 module parses it out.

这篇关于如何在对 SQLite3 的 Python 调用中获取可变长度占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆