我有一个元组列表,我将其插入表中。
每个元组有50个值。如何插入而不必指定列名和有多少?
?
col1
是一个自动增量列,因此我的insert stmt在col2
中开始,以col51
结尾。
当前代码:
l = [(1,2,3,.....),(2,4,6,.....),(4,6,7,.....)...]
for tup in l:
cur.execute(
"""insert into TABLENAME(col2,col3,col4.........col50,col51)) VALUES(?,?,?,.............)
""")
想:
insert into TABLENAME(col*) VALUES(*)
答案 0 :(得分:1)
这里记录了MySQL的INSERT语法:http://dev.mysql.com/doc/refman/5.7/en/insert.html
没有像你所示的通配符语法。最接近的是省略列名:
INSERT INTO MyTable VALUES (...);
但我不建议这样做。只有当您确定要为表中的每一列(甚至是自动增量列)指定值时,它才有效,并且保证您的值与表的列的顺序相同。
您应该学会使用代码根据应用程序中的值数组构建SQL查询。这是我的一个Python示例。假设您有一个名为data_values
的列:值对的字典。
placeholders = ['%s'] * len(data_values)
sql_template = """
INSERT INTO MyTable ({columns}) VALUES ({placeholders})
"""
sql = sql_template.format(
columns=','.join(keys(data_values)),
placeholders=','.join(placeholders)
)
cur = db.cursor()
cur.execute(sql, data_values)
答案 1 :(得分:0)
要放在代码之前的示例代码:
cols = "("
for x in xrange(2, 52):
cols = cols + "col" + str(x) + ","
test = test[:-1]+")"
在你的循环中
for tup in l:
cur.execute(
"""insert into TABLENAME " + cols " VALUES {0}".format(tup)
""")
这是我的头脑,没有错误检查