【问题标题】:sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near [duplicate]sqlalchemy.exc.ProgrammingError:(psycopg2.errors.SyntaxError)在[重复]处或附近出现语法错误
【发布时间】:2020-08-20 00:24:38
【问题描述】:

[PostgreSQL] 我想执行一个带有插入变量的 SELECT 查询,以从 URL 命令查询以在我的数据库中搜索一些数据,当我将变量传递给 SELECT 查询时一切正常,但它给了我一个错误:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) 在“0380795272”或附近出现语法错误

第 1 行:SELECT * FROM books WHERE title LIKE '%'0380795272'%'

^

routes.py:

@app.route("/search", methods=['GET']) 
def search():
    form = SearchForm()
    search_field = request.args.get('query')
    db_books = db1.execute("SELECT * FROM books WHERE title LIKE '%:search%'", {"search": search_field}).fetchall() //this is the line where I have an error
    if db_books:
        return render_template("index.html", title="index", db_books=db_books, form=form, search_field=search_field)
    else:
        flash('There is no such book', 'danger')
        return render_template("index.html", db_books=db_books, form=form)

models.py:

class Books(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    isbn = db.Column(db.String(100))
    title = db.Column(db.String(100))
    author = db.Column(db.String(100))
    year = db.Column(db.String(20))

    def __repr__(self):
        return f"Books('{self.isbn}', '{self.title}', '{self.author}')"

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    数据库拒绝查询,因为搜索词周围有多余的引号:

    SELECT * FROM books WHERE title LIKE '%'0380795272'%'
    

    添加引号是因为绑定参数:search 被自动引用:

    db1.execute("SELECT * FROM books WHERE title LIKE '%:search%'", {"search": search_field})
    

    解决方案是将“%”通配符添加到搜索词中,而不是将它们放在查询中

    db1.execute("SELECT * FROM books WHERE title LIKE :search",
                {"search": '%{}%'.format(search_field)}) 
    

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 2018-04-21
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多