2016-10-04 90 views
0

比方说,我有客户ID的Python列表如下:select name where id =“in the python list”?

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) 

运行的代码后,我什么也没有插入到表中。我有什么错误?

请帮助:(

+3

谨防[鲍比表(https://xkcd.com/327/)。 –

+0

编程不是/完全/神奇;) – hop

回答

0

您需要格式化字符串。

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

参数化的sql会更好。请参阅http://stackoverflow.com/questions/8671702/passing-list-of-parameters-to-sql-in-psycopg2 – hop

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) 
相关问题