Flask Snippets

Simple insertion and row id

By WillyFrog filed in Database

This function lets you abstract the insertion into the database and get it's last id. This example uses sqlite3.

def insert(table, fields=(), values=()):
    # g.db is the database connection
    cur = g.db.cursor()
    query = 'INSERT INTO %s (%s) VALUES (%s)' % (
        ', '.join(fields),
        ', '.join(['?'] * len(values))
    cur.execute(query, values)
    id = cur.lastrowid
    return id

This snippet by WillyFrog can be used freely for anything you like. Consider it public domain.