【问题标题】:python sqlite3 .executemany() with named placeholders?python sqlite3 .executemany() 与命名占位符?
【发布时间】:2018-05-02 04:48:31
【问题描述】:

这行得通:

ss = 'insert into images (file_path) values(?);'
dddd = (('dd1',), ('dd2',))
conn.executemany(ss, dddd)

但事实并非如此:

s = 'insert into images (file_path) values (:v)'
ddddd = ({':v': 'dd11'}, {':v': 'dd22'})
conn.executemany(s, ddddd)
Traceback (most recent call last):
  File "/Users/Wes/.virtualenvs/ppyy/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 3035, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-31-a999de59f73b>", line 1, in <module>
    conn.executemany(s, ddddd)
ProgrammingError: You did not supply a value for binding 1.

我想知道是否可以将命名参数与 executemany 一起使用,如果可以,如何使用。

第 11.13.3 节中的 documentation 一般谈论参数,但没有讨论为其他风格的 .executexxx() 描述的两种参数样式。

我查看了与 executemany 无关的 Python sqlite3 execute with both named and qmark parameters。

【问题讨论】:

    标签: python-2.7 sqlite


    【解决方案1】:

    source 表明execute() 只是构造了一个单元素列表并调用executemany(),所以问题不在于executemany() 本身;相同的调用失败,execute():

    >>> conn.execute('SELECT :v', {':v': 42})
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    sqlite3.ProgrammingError: You did not supply a value for binding 1.
    

    如Python documentation所示,命名参数不包含冒号:

    # And this is the named style:
    cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
    

    所以你必须使用ddddd = ({'v': 'dd11'}, {'v': 'dd22'})。

    【讨论】:

      【解决方案2】:

      : 不是参数名称的一部分。

      >>> s = 'insert into images (file_path) values (:v)'
      >>> ddddd = ({'v': 'dd11'}, {'v': 'dd22'})
      >>> conn.executemany(s, ddddd)
      <sqlite3.Cursor object at 0x0000000002C0E500>
      >>> conn.execute('select * from images').fetchall()
      [(u'dd11',), (u'dd22',)]
      

      【讨论】:

      • 很抱歉我不能给你们两个打勾。
      猜你喜欢
      • 2012-08-24
      • 2019-08-06
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 2017-12-11
      • 2014-10-17
      • 1970-01-01
      相关资源
      最近更新 更多