从动态列表

时间:2016-02-02 01:50:08

标签: python mysql

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

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()

文件内容为例:

{"lines": [[2, 12121, 33, 44, "ff"], [2, 786, 33, 66, "ww"]], "columns": ["id", "testnumber", "size", "gnumber", "filenname"]}

打印出有趣的值int表是:

INSERT INTO test8(id,testnumber,size,gnumber,filenname) VALUES (2,786,33, 66,ww,test)

我得到的错误是:

  

追踪(最近一次通话):         文件“pp.py”,第50行,in           c.execute(insert_intotable)         文件“/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py”,第174行,执行           self.errorhandler(self,exc,value)         在defaulterrorhandler中输入文件“/usr/lib/python2.7/dist-packages/MySQLdb/connections.py”,第36行           提出错误类,错误值       _mysql_exceptions.ProgrammingError:(1064,“您的SQL语法有错误;请查看与您的MySQL对应的手册   服务器版本,用于在第1行“ww,test”附近使用正确的语法“”

任何帮助将不胜感激:)

0 个答案:

没有答案