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

前端 未结 8 1565
刺人心
刺人心 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).

    0 讨论(0)
  • 2020-12-02 12:11

    You have to give %% to use it as % because % in python is use as string formatting so when you write single % its assume that you are going to replace some value with this.

    So when you want to place single % in string with query allways place double %.

    0 讨论(0)
  • 2020-12-02 12:14

    This could also result from the case - in case parameters to be passed onto the SQL are declared in DICT formate and are being manipulated in the SQL in the form of LIST or TUPPLE.

    0 讨论(0)
  • 2020-12-02 12:15

    It seems like your problem may be related to this bug.

    In which case, you should triple-escape as a workaround.

    0 讨论(0)
  • 2020-12-02 12:18

    SQLAlchemy has a text() function for wrapping text which appears to correctly escape the SQL for you.

    I.e.

    res = executeSql(sqlalchemy.text(sql))
    

    should work for you and save you from having to do the manual escaping.

    0 讨论(0)
  • 2020-12-02 12:18

    I found one more case when this error shows up:

    c.execute("SELECT * FROM t WHERE a = %s")
    

    In other words, if you provide parameter (%s) in query, but you forget to add query params. In this case error message is very misleading.

    0 讨论(0)
提交回复
热议问题