为什么这不起作用?在哪里

时间:2017-03-03 18:03:53

标签: python python-3.x sqlite

(不重复。我知道有一种方法可以做到这一点:Parameter substitution for a SQLite "IN" clause。)

我想知道代码中缺少的内容。我构建了一个简单的表。然后我成功地将其一些记录复制到一个新表中,其中记录由涉及两个列表的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!

1 个答案:

答案 0 :(得分:3)

SQL参数的重点是阻止值中的SQL语法被执行。这包括值之间的逗号;如果不是这种情况,那么你就不能在查询参数中使用带逗号的值,这可能是引导的安全问题。

您不能只使用一个?在查询中插入多个值;整个TextTemp值被视为一个值,产生以下等价物:

create table newTable as 
select * from oldTable
where ColA in ('15,3,44,9') or ColB in ('15,3,44,9')

ColAColB中的所有值都没有一行,其字符串值为15,3,44,9

您需要为参数中的每个值使用单独的占位符

col_values = [int(v) for v in "15 3 44 9".split()]

placeholders = ', '.join(['?'] * len(col_values))
sql = '''create table newTable as 
    select * from oldTable
    where ColA in ({0}) or ColB in ({0})'''.format(placeholders)

curs.execute(sql, col_values * 2)