Python 为什么可以';我不能获取数据库lastrowid吗?

Python 为什么可以';我不能获取数据库lastrowid吗?,python,python-3.x,sqlite,flask,flask-wtforms,Python,Python 3.x,Sqlite,Flask,Flask Wtforms,我想记录表单数据并将其传递到另一个页面,所以我只想将(自动递增)行id传递给它,然后在下一个函数中检索它。它正确地创建了数据库条目,但是光标lastrowid总是返回None,因此我无法获取下一页的数据 def connect_db(): """Connects to the database.""" rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row return r

我想记录表单数据并将其传递到另一个页面,所以我只想将(自动递增)行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')
def connect_db():
“”“连接到数据库。”“”
rv=sqlite3.connect(app.config['DATABASE'])
rv.row_工厂=sqlite3.row
返回rv
def get_db():
“”“如果尚未建立数据库连接,则打开新的数据库连接。”
当前应用程序上下文。
"""
如果不是hasattr(g,'sqlite_db'):
g、 sqlite_db=connect_db()
返回g.sqlite_db
@app.route('/choose',methods=['GET','POST'])
def输入_值():
form=UserValuesForm()
if form.validate_on_submit():
g、 db=get_db()
g、 db.execute('插入到请求中(占用者,'
'变速箱型、驱动型、发动机型、燃油经济性'
“行李箱容量、牵引容量、安全等级”
“值(?,,,,,,,,,,,,,,)”,
[form.accumbers.data';'。连接(form.transmission_type.data),
“;”.join(form.drive_type.data),“;”.join(form.engine_type.data),
form.fuel_economy.data,form.trunk_capacity.data,
表格.拖航能力.数据,表格.安全等级.数据])
g、 last_req_id=g.db.cursor().lastrowid
g、 db.commit()
返回重定向('results/{0}'。格式(str(g.last_req_id)))
返回呈现模板('choose.html',form=form)
@app.route('/results/',methods=['GET'])
def结果(请求id):
返回渲染模板('results.html')

另外,还有更好的方法吗?

您尝试从一个全新的光标获取值。您希望使用从中获取值的光标执行插入

cursor = g.db.cursor()
cursor.execute('...')
g.last_req_id = cursor.lastrowid
g.db.commit()
此外,您不需要将
last_req_id
g
关联,因为您所做的只是在
输入值中本地使用它

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

您还会看到我删除了对
str
的调用<代码>格式
将为您处理此问题

除非它是Python绑定中的一个限制,否则在提交之前最后一行id确实是可用的。@ColonelThirtyTwo您是对的。谢谢修好柱子。非常感谢!我很困惑,因为数据库连接g.db具有创建条目所需的execute方法,所以我没有意识到需要显式创建游标对象。