使用 Flask 在 sqlite3 数据库中添加数据时出错

我试图在现有数据库中添加数据但得到错误输出,有一个小错误请帮助我。谢谢


代码 ::


@app.route('/')

def new_student():

    return render_template('student.html')


@app.route('/addrec', methods=['POST', 'GET'])


def addrec():

    if request.method == 'POST':

        try:

            nm = request.form['nm']

            addr = request.form['add']

            city = request.form['city']

            pin = request.form['pin']


            with sql.connect("database.db") as con:

                cur = con.cursor()

                cur.execute('''INSERT INTO students (name,addr,city,pin)

                    VALUES(?, ?, ?, ?)''',(nm,addr,city,pin))


                con.commit()

                msg = "Record successfully added"

        except:


            con.rollback()

            msg = "error in insert operation"


        finally:

            return render_template("result.html", msg=msg)

            con.close()


if __name__ == '__main__':

    app.run(debug=True)

我的 result.html 文件是:


<!doctype html>

<html>

   <body>

      result of addition : {{ msg }}

      <h2><a href = "\">go back to home page</a></h2>

   </body>

</html>

输出应该是::“记录已成功添加”,但我收到“插入操作中的错误”。


一只萌萌小番薯
浏览 269回答 3
3回答

qq_花开花谢_0

我的猜测是你的代码中有一个错字:addr = request.form['add']应该addr = request.form['addr']但是您的代码需要一些关于连接的修复:con.commit()在with块的正常退出时con.rollback()调用,并且在with块因异常退出时调用。您不需要这两个显式调用。此外,您con.close()在return语句之后放置了,这意味着它将永远不会被执行。只需交换线路,或考虑在程序开始时打开连接。

梵蒂冈之花

为此挣扎了好几个小时。首先,您需要创建一个python文件并运行它来创建一个数据库。之后运行主python文件。它对我有用。无需将“add”更改为“addr”,因为在student.html中,名称被指定为“add” 还要创建一个home.html文件<!DOCTYPE HTML>&nbsp;&nbsp;<HTML>&nbsp;&nbsp;<head>&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;<title>home</title>&nbsp;&nbsp;</head>&nbsp;&nbsp;<body>&nbsp;&nbsp;&nbsp; &nbsp;<h2>Hi, welcome to the website</h2>&nbsp;&nbsp;&nbsp; &nbsp;<a href="/enternew">Add New Record</a><br><be>&nbsp;&nbsp;&nbsp; &nbsp;<a href ="/list">Show List</a><br><be>&nbsp;&nbsp;</body>&nbsp;&nbsp;</html>&nbsp;

慕斯王

在 之后except:,放一个raise重新引发最后一个异常并在此处发布回溯。可能的问题是:您对 database.db 文件没有权限您没有发送表单键之一,并且访问request.form["some key"]正在引发 KeyError 异常。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python