首页 > 解决方案 > 将多个变量传递给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,))

标签: pythonsqlsqlite

解决方案


使用显式编号的参数(?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 端使用它们。


推荐阅读