Python 从动态列表插入到表中

Python 从动态列表插入到表中,python,mysql,Python,Mysql,我使用动态方法创建表,然后将值插入其中。有两个从不同文件动态填充的列表,这些列表的数量可以增加或减少,并且值每次都在更改。我的问题是,我设法动态创建了带有字段的表,但在向表中插入值时仍然存在一些问题。这是我的密码: f = open(filepath,"r") pluginoutput= f.read() pluginoptojson = json.loads(pluginoutput) columnsnames = (pluginoptojson["columns"]) countcolumn

我使用动态方法创建表,然后将值插入其中。有两个从不同文件动态填充的列表,这些列表的数量可以增加或减少,并且值每次都在更改。我的问题是,我设法动态创建了带有字段的表,但在向表中插入值时仍然存在一些问题。这是我的密码:

f = open(filepath,"r")
pluginoutput= f.read()
pluginoptojson = json.loads(pluginoutput)
columnsnames = (pluginoptojson["columns"])
countcolumns = len(pluginoptojson["columns"])
count = 0
lst = []
for name in columnsnames:
    if count < countcolumns:
        lst.append(str(name))
        count +=1

lst.append("caseid")
table_name = "test2"
createsqltable = """CREATE TABLE IF NOT EXISTS """ + table_name + " (" + " VARCHAR(50),".join(lst) + " VARCHAR(50))"
print createsqltable
c.execute(createsqltable)
conn.commit()

#c.close()
#conn.close()
#gc.collect()


rowsvalue = (pluginoptojson["rows"])

for row in rowsvalue:
    lst2 =[]
    rowelementscount = len(row)
    for value in row:
        lst2.append(str(value))
    lst2.append("test")
    insert_intotable = "INSERT INTO "  + table_name + "(" + ",".join(lst) + ") VALUES (" + ",".join(lst2) +")"
    print insert_intotable
    c.execute(insert_intotable)
    conn.commit()
c.close()
conn.close()
gc.collect()
有趣值int表的打印输出为:

INSERT INTO test8(id,testnumber,size,gnumber,filenname) VALUES (2,786,33, 66,ww,test)
我得到的错误是:

回溯(最近一次呼叫最后一次): 文件“pp.py”,第50行,在 c、 执行(插入表格) 文件“/usr/lib/python2.7/dist packages/MySQLdb/cursors.py”,执行中的第174行 errorhandler(self、exc、value) 文件“/usr/lib/python2.7/dist packages/MySQLdb/connections.py”,第36行,在defaulterrorhandler中 提高errorclass,errorvalue _mysql_exceptions.ProgrammingError:(1064),“您的SQL语法有错误;请检查与您的mysql对应的手册 第1行“ww,test)”附近要使用的正确语法的服务器版本)


任何帮助都将不胜感激:)

您关闭光标和连接,然后尝试插入语句……是的,您是对的,我对其进行了编辑,但仍然存在语法错误
ww
test
需要是字符串。您应该使用参数化查询。由于输入不可信,您的设计容易受到SQL注入攻击。我已将它们全部转换为字符串,但现在很幸运,谢谢您的安全提示。
INSERT INTO test8(id,testnumber,size,gnumber,filenname) VALUES (2,786,33, 66,ww,test)