这有效:
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()描述的两种参数样式。
我检查了Python sqlite3 execute with both named and qmark parameters与executemany无关。
答案 0 :(得分:2)
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'})
。
答案 1 :(得分:1)
:
不是参数名称的一部分。
>>> 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',)]