试图通过sqlalchemy将数据插入数据库时出现语法错误

2024-07-04 05:48:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉python和web开发。我正在尝试执行这个SQL alchemy insert命令(我从视频中看到了它),但它给了我语法错误。我无法理解炼金术文档

@app.route("/")
def index():
    id = "Vishal"
    p = "vishal94"
    connection.execute("INSERT INTO books (username , password) VALUES(:username , :password)",{"username":id, "password":p})
    dat = connection.execute("select * from books")
    return render_template("data.html",dat = dat)


sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near ":"
LINE 1: INSERT INTO books (username , password) VALUES(:username , :...
                                                       ^

[SQL: INSERT INTO books (username , password) VALUES(:username , :password)]
[parameters: {'username': 'Vishal', 'password': 'vishal94'}]
(Background on this error at: http://sqlalche.me/e/f405)

我实际上是从cs50课程视频中复制了这个命令,但仍然不起作用


Tags: 命令idexecutesql视频usernamepasswordconnection
2条回答

"INSERT INTO books (username , password) VALUES(:username , :password)"包装在text()

text("INSERT INTO books (username , password) VALUES(:username , :password)")

我认为:variable语法要求

您可以使用%(key)s为您的查询定义关键字参数

@app.route("/")
def index():
    id = "Vishal"
    p = "vishal94"
    connection.execute("INSERT INTO books (username , password) VALUES (%(username)s, %(password)s)", {"username":id, "password":p})
    dat = connection.execute("select * from books")
    return render_template("data.html",dat = dat)

相关问题 更多 >

    热门问题