python - 将多个变量传递给python中的SQLite查询
问题描述
我在 python 代码中有一个 SQLite 查询(如下所示),它使用版本号作为“字符串”,我必须将这些版本(以下查询中的“1.2.7”和“3.7.10”)作为变量(v1, v2)。
我成功地使用了“?” 为“name”属性传递一个变量(pname)。我不确定如何在多次出现的 SQLite 查询中传递多个变量。
c.execute( """
select name,version from packages
where name = ? and
1000000 * replace(version, '.', 'x') +
1000 * replace(substr(version, instr(version, '.') + 1), '.', 'x') +
replace(version, '.', '000') % 1000
between
1000000 * replace('1.2.7', '.', 'x') +
1000 * replace(substr('1.2.7', instr('1.2.7', '.') + 1), '.', 'x') +
replace('1.2.7', '.', '000') % 1000
and
1000000 * replace('3.7.10', '.', 'x') +
1000 * replace(substr('3.7.10', instr('3.7.10', '.') + 1), '.', 'x') +
replace('3.7.10', '.', '000') % 1000
""" ,(pname,))
就像是:
c.execute( """
select name,version from packages
where name = ? and
1000000 * replace(version, '.', 'x') +
1000 * replace(substr(version, instr(version, '.') + 1), '.', 'x') +
replace(version, '.', '000') % 1000
between
1000000 * replace(V1, '.', 'x') +
1000 * replace(substr(V1, instr(V1, '.') + 1), '.', 'x') +
replace(V1, '.', '000') % 1000
and
1000000 * replace(V2, '.', 'x') +
1000 * replace(substr(V2, instr(V2, '.') + 1), '.', 'x') +
replace(V2, '.', '000') % 1000
""" ,(pname,))
解决方案
使用显式编号的参数(?1
指第一个绑定值,?2
指第二个,依此类推):
c.execute( """
select name,version from packages
where name = ?1 and
1000000 * replace(version, '.', 'x') +
1000 * replace(substr(version, instr(version, '.') + 1), '.', 'x') +
replace(version, '.', '000') % 1000
between
1000000 * replace(?2, '.', 'x') +
1000 * replace(substr(?2, instr(?2, '.') + 1), '.', 'x') +
replace(?2, '.', '000') % 1000
and
1000000 * replace(?3, '.', 'x') +
1000 * replace(substr(?3, instr(?3, '.') + 1), '.', 'x') +
replace(?3, '.', '000') % 1000
""" ,(pname,v1,v2))
您也可以使用命名参数而不是编号,但我不确定如何在 Python 端使用它们。
推荐阅读
- r-markdown - 我无法编织我的 rmarkdown 文件 - pandoc 错误
- reactjs - 如何防止在 webpack 中使用 react monaco 之前被加载?
- direct3d9 - &D3DXVECTOR3 导致错误 C2102 '&' 需要左值
- date - 计算列中大于 Google 表格/Excel 中当前日期的日期数
- c# - 使用 FFI 将字符串从 C# 传递到 Rust
- javascript - 从响应中的输入发送值(将 querySelector(id) 更改为响应)
- swagger - springfox swagger中的多态性
- javascript - 如何使用 css 和 bootstrap 进行制表符
- python - 将熊猫列值转换为列
- python-3.x - ImportError:在运行管理命令时无法从 django.db.models.fields 导入 FiledDoesNotExist