python的插入查询
我有一个名为mylist的列表,它生成的结果是(1,2,3,4) 有没有一种编写查询的好方法,只使用整个列表作为值 我知道怎么做的唯一方法就是python的插入查询,python,mysql,Python,Mysql,我有一个名为mylist的列表,它生成的结果是(1,2,3,4) 有没有一种编写查询的好方法,只使用整个列表作为值 我知道怎么做的唯一方法就是 INSERT INTO table (col1,col2,col3,col4) VALUES ('%s','%s','%s','%s') % (mylist[0],mylist[1],mylist[2],mylist[3]) 我想这应该行得通: "INSERT INTO table (col1,col2,col3,col4) VALUES ('%s',
INSERT INTO table (col1,col2,col3,col4) VALUES ('%s','%s','%s','%s') % (mylist[0],mylist[1],mylist[2],mylist[3])
我想这应该行得通:
"INSERT INTO table (col1,col2,col3,col4) VALUES ('%s','%s','%s','%s')" % tuple(mylist)
下面是一个使用格式的好方法:
"INSERT INTO table (col1,col2,col3,col4) VALUES ('{0[0]}','{0[1]}','{0[2]}','{0[3]}')".format(mylist)
如果不知道元组的长度,可以采用更通用的方式:
valuesstr = "("
for i in range(0,len(mylist)): # Do this once for every list item.
valuesstr += "'" + str(mylist[i]) + "'" # Add a value automatically.
if i+1 < len(mylist): # See if we've reached the end yet.
valuesstr += "," # Add separating commas.
valuesstr += ")"
querystr = "INSERT INTO table (col1,col2,col3,col4) VALUES %s" % (valuesstr)
valuesstr=“(”
对于范围(0,len(mylist))中的i:#对每个列表项执行一次。
valuesstr+=“'”+str(mylist[i])+“'”#自动添加一个值。
如果i+1
但是如果你知道总是有四个项目,其他的答案就更容易了。你可以使用splat操作符来避免对每个元素的去引用:
({0}',{1}',{2}',{3}')。format(*mylist)