写一个变量的名称为一个字符串不会奇迹般地使内容出现在字符串中。
>>> p = 'some part'
>>> s = 'replace p of a string'
>>> s
'replace p of a string'
>>> s = 'replace %s of a string' % p
>>> s
'replace some part of a string'
>>> s = 'replace {} of a string'.format(p)
>>> s
'replace some part of a string'
你的情况,这将意味着:
>>> sql = "insert into cust_table (name) values (names) where cust_id IN ('%s')"
>>> ids = ", ".join(id)
>>> cursor.execute(sql % ids)
虽然我强烈怀疑您与names
有类似的问题。
为了避免可能的sql注入问题,最好使用“参数化语句”。这看起来像这样:
>>> sql = 'insert into ... where cust_id IN %s'
>>> cursor.execute(sql, (id,))
python的一些数据库连接器能够这样做,但你可能不是。
一种解决方法可能是这样的
>>> params = ', '.join(['%s']*len(id))
>>> sql = 'insert into ... where cust_id IN (%s)' % params
>>> cursor.execute(sql, id)
来源
2016-10-04 14:32:59
hop
谨防[鲍比表(https://xkcd.com/327/)。 –
编程不是/完全/神奇;) – hop