【问题标题】:Passing Array Parameter to SQL command将数组参数传递给 SQL 命令
【发布时间】:2015-06-02 06:40:46
【问题描述】:

在 Python 2.7 中,我可以像这样将参数传递给 sql 命令:

cursor.execute("select * from my_table where id = %s", [2])

我无法让数组等价物像这样工作:

cursor.execute("select * from my_table where id in %s", [[10,2]])

显然,我可以只进行字符串格式化,但如果可能的话,我想做一个适当的参数。如果这很重要,我正在使用 postgresql 数据库。

【问题讨论】:

  • I would like to do a proper parameter if possible - 这是什么意思?
  • "select * from my_table where id in (%d,%d)", [10,2]) 有什么问题?
  • 列表不是固定大小的。 %d 也适用于常规的 python 字符串格式,但在这种情况下不起作用。
  • 你为什么使用数组而不是元组,像这样:([10,2],)?

标签: python postgresql python-2.7


【解决方案1】:
cursor.execute("select * from my_table where id = ANY(%s);", [[10, 20]])

note。要使用IN,请参阅section below

cursor.execute(cursor.mogrify("select * from my_table where id in %s",
                              [tuple([10, 20])]))

【讨论】:

  • 原因是IN (1,2,3) 在任何地方都没有数组,而是一组字面值。
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 2012-08-13
  • 2015-06-09
  • 2017-10-22
  • 2021-10-20
  • 2019-10-12
  • 1970-01-01
相关资源
最近更新 更多