【问题标题】:Why doesn't this work? WHERE IN为什么这不起作用?在哪里
【发布时间】: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


【解决方案1】:

SQL 参数的全部意义在于防止值中的 SQL 语法被执行。这包括值之间的逗号;如果不是这种情况,那么您永远不能在查询参数中使用带逗号的值,这可能是一个启动的安全问题。

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

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)

【讨论】:

  • 我正想问 OP,如果你格式化它会发生什么:)
  • 我只知道这会很痛苦。
猜你喜欢
  • 2013-05-16
  • 2019-02-10
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多