为什么我无法获得数据库的lastrowid?

1 投票
1 回答
2458 浏览
提问于 2025-04-19 02:55

我想记录表单的数据,然后把这些数据传到另一个页面,所以我打算只传递一个自动增加的行ID,然后在下一个函数中获取它。数据库的记录确实创建成功了,但游标的 lastrowid 总是返回 None,所以我无法获取下一个页面的数据。

def connect_db():
    """Connects to the database."""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv


def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

@app.route('/choose', methods=['GET', 'POST'])
def input_values():
    form = UserValuesForm()
    if form.validate_on_submit():
        g.db = get_db()
        g.db.execute('insert into requests (occupants, '
                   'transmission_type, drive_type, engine_type, fuel_economy, '
                   'trunk_capacity, towing_capacity, safety_rating) '
                   'values (?, ?, ?, ?, ?, ?, ?, ?)',
                   [form.occupants.data, ';'.join(form.transmission_type.data),
                    ';'.join(form.drive_type.data), ';'.join(form.engine_type.data),
                    form.fuel_economy.data, form.trunk_capacity.data,
                    form.towing_capacity.data, form.safety_rating.data])
        g.last_req_id = g.db.cursor().lastrowid
        g.db.commit()
        return redirect('results/{0}'.format(str(g.last_req_id)))
    return render_template('choose.html', form=form)

@app.route('/results/<int:req_id>', methods=['GET'])
def result(req_id):
    return render_template('results.html')

另外,有没有更好的方法来做到这一点呢?

1 个回答

3

你想从一个全新的游标中获取值。你希望用同一个游标来执行插入操作,这样就能得到你想要的值。

cursor = g.db.cursor()
cursor.execute('...')
g.last_req_id = cursor.lastrowid
g.db.commit()

另外,你不需要把 last_req_idg 关联起来,因为你只是在 input_values 中局部使用它。

last_req_id = cursor.lastrowid
return redirect('results/{0}'.format(last_req_id))

你还会看到我去掉了对 str 的调用。其实 format 会帮你处理这个问题。

撰写回答