'SQL syntax problem-- escaping single quote and percentage sign

I am trying to do an online course on Cybersecurity and one of the problems is trying to preform an sql injection. I have not been able to figure it out because of the syntax problems and escape sequences I think.

    def query():
         return "sd UNION SELECT password FROM Users WHERE admin = 1"
    
    def main():
         conn = sqlite3.connect(dbname)
         cursor = conn.cursor()
         response = cursor.execute("SELECT body FROM Tasks WHERE name='%s' and body LIKE 
         '%%%s%%'" % (username, query())).fetchall()
         print('Found entries:')
         for r in response:
             print(r[0])

I can only edit the query() function and When I run this code the sql statement returns nothing. The last executed command that is run is this : SELECT body FROM Tasks WHERE name='bob' and body LIKE '%sd UNION SELECT password FROM Users WHERE admin = 1%'

After I realized that the quotations and '%' was causing the problems I have tried to escape them somehow but haven't been able to yet. I have tried this query = "sd'' UNION SELECT password FROM Users WHERE admin = 1''" and many other similar combinations to escape it but have had no success. To be clear all the columns exist because if I change the Unit tests and run the code as "SELECT body FROM Tasks WHERE name='bob' and body LIKE 'sd' UNION SELECT password FROM Users WHERE admin = 1" I get the password but the prepared statement version with '%%%s%%' doesn't let me pass the tests for some reason. How should I write my query so that I can escape the % and single quotations in SQLite python?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source