【发布时间】:2017-03-07 08:15:04
【问题描述】:
(不是重复的。我知道有一种方法可以做到这一点:Parameter substitution for a SQLite "IN" clause。)
我想知道我在 this 代码中缺少什么。我建立了一个简单的表。然后我成功地将它的一些记录复制到一个新表中,其中记录由涉及两个列表的 WHERE 子句限定。扔掉该表后,我尝试复制相同的记录,但这次我将列表放入一个变量中,该变量插入到 sql 语句中。这次没有记录被复制。
怎么会?
import sqlite3
conn = sqlite3.connect(':memory:')
curs = conn.cursor()
oldTableRecords = [ [ 15, 3 ], [ 2, 1], [ 44, 2], [ 6, 9 ] ]
curs.execute('create table oldTable (ColA integer, ColB integer)')
curs.executemany('insert into oldTable (ColA, ColB) values (?,?)', oldTableRecords)
print ('This goes ...')
curs.execute('''create table newTable as
select * from oldTable
where ColA in (15,3,44,9) or ColB in (15,3,44,9)''')
for row in curs.execute('select * from newTable'):
print ( row)
curs.execute('''drop table newTable''')
print ('This does not ...')
TextTemp = ','.join("15 3 44 9".split())
print (TextTemp)
curs.execute('''create table newTable as
select * from oldTable
where ColA in (?) or ColB in (?)''', (TextTemp,TextTemp))
for row in curs.execute('select * from newTable'):
print ( row)
输出:
This goes ...
(15, 3)
(44, 2)
(6, 9)
This does not ...
15,3,44,9
TIA!
【问题讨论】:
-
为什么是
TextTemp = ','.join("15 3 44 9".split())而不仅仅是'15,3,44,9'? -
因为我心不在焉。
-
这是一个很好的理由 :-)
标签: python python-3.x sqlite