how to safely generate a SQL LIKE statement using python db-api

后端 未结 3 632
悲哀的现实
悲哀的现实 2020-12-06 05:08

I am trying to assemble the following SQL statement using python\'s db-api:

SELECT x FROM myTable WHERE x LIKE \'BEGINNING_OF_STRING%\';

wh

3条回答
  •  一生所求
    2020-12-06 05:59

    EDIT:

    As Brian and Thomas noted, the far better way to do this would be to use:

    beginningOfString += '%'
    cursor.execute("SELECT x FROM myTable WHERE x LIKE ?", (beginningOfString,) )
    

    since the first method leaves you open to SQL injection attacks.


    Left in for history:

    Try:

    cursor.execute("SELECT x FROM myTable WHERE x LIKE '%s%%'" % beginningOfString)
    

提交回复
热议问题