在flask应用程序中使用sqlite获取lastrowid

问题描述 投票:0回答:1

我有一个 Flask 应用程序,其工厂模式仅使用 Sqlite。

当尝试执行“last_row = db.lastrowid”id 时,我收到错误:

AttributeError:'sqlite3.Connection'对象没有属性'lastrowid'

当我使用这个sqlite函数“last_inserted_rowid”时 https://www.w3resource.com/sqlite/core-functions-last_insert_rowid.php

我收到错误:

“类型错误:'sqlite3.Cursor'对象不可下标”

def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        # return rows that behave like dicts. This allows accessing the columns by name.
        g.db.row_factory = sqlite3.Row

    return g.db
@bp.route('/createstrat', methods=('GET', 'POST'))
@login_required
def createstrat():
    if request.method == 'POST':
        strategy_name = request.form['strategy_name']
        info = request.form['info']
        exchange = request.form['exchange']
        error = None

        if not strategy_name:
            error = 'strategy_name is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()

            db.execute(
                'INSERT INTO strategies (strategy_name, info, fk_user_id, fk_exchange_id)'
                ' VALUES (?, ?, ?, ?)',
                (strategy_name, info, g.user['id'], exchange)
            )

            db.commit()
            # Get the ID of the last inserted row??
            #this dont work
            #last_row = db.execute('SELECT last_insert_rowid()')

            last_row = db.lastrowid
            print(last_row, "LAST ROW")
            if last_row:
                last_inserted_id = last_row[0]
                print("Last inserted row ID:", last_inserted_id)

            return redirect(url_for('strategy.index'))
python sqlite flask
1个回答
0
投票

这是一种获取最后一行 id 的方法,使用 w3resource.com 建议的

last_insert_rowid()
函数。

import sqlite3
import random

db_file = "db.sqlite3"
conn = sqlite3.connect(db_file)
cur = conn.cursor()

cur.execute("INSERT INTO my_table VALUES({}, 'some text here')".format(random.randrange(100000)))
conn.commit()

cur.execute('SELECT last_insert_rowid()')
last_row = cur.fetchall()
print("last insert row id: {}".format(last_row[0]))

我建议你看一下官方文档中关于运行DDL语句(例如INSERT)和SELECT语句的区别的示例。

© www.soinside.com 2019 - 2024. All rights reserved.