尝试为execute
构建SQL语句。这可行,但现在确定它可能是多少pythonic:
user_fields = ("id", "name", "email", "password", "phone")
fields = [field for field in user_fields if field != "id"] # The only field we don't want is "id"
percent_s = ["%s"] * len(fields)
fields = ",".join(fields)
percent_s = ",".join(percent_s)
sql = "INSERT INTO user_table (" + fields + ") VALUES (" + percent_s + ")"
cursor.execute(sql, row_data)
答案 0 :(得分:1)
您可以替换:
sql = "INSERT INTO user_table (" + fields + ") VALUES (" + percent_s + ")"
与
sql = "INSERT INTO user_table ({}) VALUES ({})".format(fields,percent_s)
答案 1 :(得分:1)
如果您的user_fields
有固定订单,row_data
必须有相应的订单。你必须在某个地方确保这一点。然后id
的位置也是固定的。然后你可以使用字符串格式,这导致:
user_fields = ("id", "name", "email", "password", "phone")
sql = "INSERT INTO user_table (%s) VALUES (%s)" % (','.join(user_fields[1:], ','.join(['%s'] * (len(user_fields) - 1))
cursor.execute(sql, row_data)