Python 中字典的Key值与数据库中的每列的列名一一对应,列的值与字典的key的值对应即可完成直接将字典转化为insert语句代码如下
def drictToStrStock(nowData,tableName):
sql1="insert into "+tableName+" ("
sql2=" values ("
retData=""
retList=[]
for k in nowData:
retData=""
sql1="insert into "+tableName+" ("
sql2=" values ("
for i,j in k.items():
sql1+=str(i)
sql1+=","
if(type(j) is str):
sql2+='\''+str(j)+'\''
else:
sql2+=str(j)
sql2+=","
sql1=sql1[0:-1]+")"
sql2=sql2[0:-1]+")"
retData=sql1+sql2
retList.append(retData)
return retList
转化完成后通过遍历将retList数据取出来,然后通过数据库的接口发送至数据库中执行即可。