gpt4 book ai didi

python - 是否有更 pythonic 的方法来构建 INSERT 语句?

转载 作者:行者123 更新时间:2023-11-29 12:11:32 25 4
gpt4 key购买 nike

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

最佳答案

你可以替换:

sql = "INSERT INTO user_table (" + fields + ") VALUES (" + percent_s + ")"

sql = "INSERT INTO user_table ({}) VALUES ({})".format(fields,percent_s)

关于python - 是否有更 pythonic 的方法来构建 INSERT 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32171818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com