在Python中构造SQL INSERT查询的惯用法

时间:2014-06-03 15:40:39

标签: python sql insert

我有一些代码可以在表中插入一些值。看起来有点笨重 - 有更简洁的方式吗?

单词是词典列表,条目包含我不想插入的其他字段。

    # add the list of words to the words table
    time_stamp = datetime.datetime.now().isoformat()
    sql = "INSERT INTO words (word, user_id, game_id, score, time_stamp) VALUES "
    vals = []
    for word in words:
        vals.append("('%s', %s, %s, %s, '%s')" %
                    (word['str'], user_id, game_id, word['score'], time_stamp))
    cur.execute(sql + ",".join(vals))

1 个答案:

答案 0 :(得分:0)

你可以做到这一点:

tupleOfValues = [ value1, value2, value3, value4, value5]
cur.execute("INSERT INTO words (word, user_id, game_id, score, time_stamp) VALUES (?,?,?,?,?)", tupleOfValues)

cur.execute("INSERT INTO words (word, user_id, game_id, score, time_stamp) VALUES (?,?,?,?,?)", [ value1, value2, value3, value4, value5])