Strange SQLAlchemy error message: TypeError: 'dict' object does not support indexing

前端 未结 8 1595
刺人心
刺人心 2020-12-02 11:53

I am using hand crafted SQL to fetch data from a PG database, using SqlAlchemy. I am trying a query which contains the SQL like operator \'%\' and that seems to throw SqlAlc

8条回答
  •  孤街浪徒
    2020-12-02 12:08

    Another way of solving your problem, if you don't want to escape % characters or use sqlalchemy.text(), is to use a regular expression.

    Instead of:

    select id from ref_geog where short_name LIKE '%opt'
    

    Try (for case-sensitive match):

    select id from ref_geog where short_name ~ 'opt$' 
    

    or (for case-insensitive):

    select id from ref_geog where short_name ~* 'opt$'
    

    Both LIKE and regex are covered in the documentation on pattern matching.

    Note that:

    Unlike LIKE patterns, a regular expression is allowed to match anywhere within a string, unless the regular expression is explicitly anchored to the beginning or end of the string.

    For an anchor, you can use the assertion $ for end of string (or ^ for beginning).

提交回复
热议问题