选择名称,其中id =“在python列表中”?

时间:2016-10-04 13:59:54

标签: python mysql

假设我有一个客户ID的python列表,如下所示:

id = ('12','14','15','11',.......)

数组中有1000个值,我需要根据上面列表中的ID将客户名称插入表中。

我的代码就像:

ids = ",".join(id)
sql = "insert into cust_table(name)values(names)where cust_id IN('ids')"
cursor.execute(sql)

运行代码后,我没有在表中插入任何内容。我有什么错误?

请帮助:(

2 个答案:

答案 0 :(得分:0)

您需要格式化字符串。

ids = ",".join(id)
sql = "insert into cust_table(name)values(names)where cust_id IN('{ids}')"
cursor.execute(sql.format(ids= ids))

答案 1 :(得分:0)

简单地将变量的名称写入字符串并不会神奇地使其内容出现在字符串中。

>>> 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)