为什么这样不行?在哪里

2024-04-26 13:39:51 发布

您现在位置:Python中文网/ 问答频道 /正文

(不是复制品。我知道有一种方法是有效的: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

蒂亚!你知道吗


Tags: infromexecute记录tablethisselectrow
1条回答
网友
1楼 · 发布于 2024-04-26 13:39:51

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)

相关问题 更多 >