假设我有一个客户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)
运行代码后,我没有将任何内容插入到表中。我有什么错误吗?
请帮忙:
你需要格式化字符串
ids = ",".join(id)
sql = "insert into cust_table(name)values(names)where cust_id IN('{ids}')"
cursor.execute(sql.format(ids= ids))
简单地将变量名写入字符串并不能神奇地使其内容出现在字符串中。
>>> 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)