Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python列表运行SQL查询_Python_Sql_List - Fatal编程技术网

使用Python列表运行SQL查询

使用Python列表运行SQL查询,python,sql,list,Python,Sql,List,我有一个带字符串的列表: list = ['abc', 'cbd', 'bdc'] 我想将其用作SQL查询中的输入,如: query=('SELECT * from table where column1 in list') 要让SQL为列表的这3项运行,最好的方法是什么?首先,可以将列表转换为字符串,然后将其添加到查询中: My_list =['abc', 'cbd', 'bdc'] slist=" '" for i in My_list: slist+= i.strip()+

我有一个带字符串的列表:

list = ['abc', 'cbd', 'bdc']
我想将其用作SQL查询中的输入,如:

query=('SELECT * from table where column1 in list')

要让SQL为列表的这3项运行,最好的方法是什么?

首先,可以将列表转换为字符串,然后将其添加到查询中:

My_list =['abc', 'cbd', 'bdc']
slist=" '"
for i in My_list:
      slist+= i.strip()+"', '"
slist=slist[:-3]
query='''SELECT * from table where column1 in (%s)'''%slist

首先,可以将列表转换为字符串,然后将其添加到查询中:

My_list =['abc', 'cbd', 'bdc']
slist=" '"
for i in My_list:
      slist+= i.strip()+"', '"
slist=slist[:-3]
query='''SELECT * from table where column1 in (%s)'''%slist

像这样生成SQL文本通常是个坏主意()。公共数据库访问库将为您执行查询参数替换(psycopg for PostgreSQL和MySQLdb for MySQL都执行此操作,其他的则不确定)

也就是说,如果您非常确定在数组中传递的值是安全的,那么可以执行以下操作

my_list =['abc', 'cbd', 'bdc'] # do not call your variable list, list is a type
query = 'SELECT * from table where column1 in {}'.format(tuple(my_list))

像这样生成SQL文本通常是个坏主意()。公共数据库访问库将为您执行查询参数替换(psycopg for PostgreSQL和MySQLdb for MySQL都执行此操作,其他的则不确定)

也就是说,如果您非常确定在数组中传递的值是安全的,那么可以执行以下操作

my_list =['abc', 'cbd', 'bdc'] # do not call your variable list, list is a type
query = 'SELECT * from table where column1 in {}'.format(tuple(my_list))

可能重复的可能重复的可能重复的感谢,但它仍然读取最后一个逗号,因此它给出了一个错误。感谢,但它仍然读取最后一个逗号,因此它给出了一个错误。