有更多pythonic方法来构建INSERT语句吗?

时间:2015-08-23 21:40:05

标签: python postgresql

尝试为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)

2 个答案:

答案 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)