Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED] [sqlite] ? + LIKE?
#1
Question 
Hello,

Google didn't help. I tried a bunch of things, but still can't find how to use the ? syntax to prevent SQL injection while still using the LIKE operator.

book = input("Words to search for? ")
conn = sqlite3.connect(MYDB)
cur = conn.cursor()

#BAD cur.execute("SELECT DISTINCT title FROM books WHERE title LIKE '?'", "%book%")
#BAD cur.execute("SELECT DISTINCT title FROM books WHERE title LIKE '%?%'", book)
cur.execute("SELECT DISTINCT title FROM books WHERE title LIKE '%%?%%'", book)
for row in cur.fetchall():
	print(row[0])

conn.close()
Thank you.
Reply
#2
Don't know about sqlite, never used it.

In PHP, PDO is an abstraction layer, you never use the raw user input. PDO protects you from the bad guys!

Quote:SELECT * FROM users WHERE name = '' OR 1=1 --'
Check out phpdelusions.com

Using PHP you can make statements using PDO and ? like this:

Quote:$sql = "UPDATE users SET name = ? WHERE id = ?";
$pdo->prepare($sql)->execute([$name, $id]);

I have made insert queries, using python to create the PHP code, with 100s of ?s, works fine. You have to prepare then pipe to execute.

sqlite will work along the same lines, I presume
Reply
#3
(Sep-15-2026, 08:53 PM)Winfried Wrote: #BAD cur.execute("SELECT DISTINCT title FROM books WHERE title LIKE '?'", "%book%")

This is close, but "%book%" is just a string which is partly the word "book", not the value in the book variable. While you don't want to use string concatenation in the SQL statement, you can use concatenation to add the percent signs for your query.

user_string = "Harry Potter"
query_string = f"%{user_string}%" # is %Harry Potter%
You don't need quotes around the placeholder (the ?).

The final thing is that instead of just passing the string to insert in the placeholder, you have to pass it in as a list or a tuple.

So you could do your example as:

cur.execute("SELECT DISTINCT title FROM books WHERE title LIKE ?", [f"%{book}%"])
The fstring adds the percent signs for the query, and the brackets create a list of parameters.
Reply
#4
import sqlite3
from pathlib import Path


def places(description: str):
    data = {"descr": description}
    query = (
        "SELECT url, description FROM moz_places WHERE instr(description, :descr) > 0;"
    )
    #                                                         Placeholder  ^^^^
    for places in Path.home().joinpath(".mozilla/firefox").glob("*/places.sqlite"):
        with sqlite3.connect(places) as db:
            try:
                for url, desc in db.execute(query, data):
                    print(url)
            except sqlite3.OperationalError:
                print(f"{places} is locked.")


if __name__ == "__main__":
    places("Python")
Or if you want to use template string, you could use tsql:
import sqlite3
from pathlib import Path

import tsql


def places(description: str):
    query, data = tsql.render(
        t"SELECT url, description FROM moz_places WHERE instr(description, {description}) > 0;"
    )
    # tsql.render renders the template string and prevents code injection
    # it uses Template Strings, which requires Python 3.14+
    for places in Path.home().joinpath(".mozilla/firefox").glob("*/places.sqlite"):
        with sqlite3.connect(places) as db:
            try:
                for url, desc in db.execute(query, data):
                    print(url)
            except sqlite3.OperationalError:
                print(f"{places} is locked.")


if __name__ == "__main__":
    places("Python")
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
Can't figure how quoting works in this forum

bowlofred > This is close, but "%book%" is just a string which is partly the word "book", not the value in the book variable. While you don't want to use string concatenation in the SQL statement, you can use concatenation to add the percent signs for your query.→ [f"%{book}%"])

Thanks!
Reply
#6
Python's DB API 2.0, which basically all SQL DB modules follow, define the way for safe parametrized queries. For SQLite, it's even mentioned in the Python docs: https://docs.python.org/3/library/sqlite...ql-queries.

Please note that other DB modules, especially those for MySQL, may expect %s as a placeholder and to not accept the ? used in SQLite and other RDBMS.

Regards, noisefloor
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Solved]Help with SQLite Login Form Extra 7 5,590 Jun-25-2022, 10:53 AM
Last Post: deanhystad
  [Solved]Help with search statement-SQLite & Python Extra 1 2,652 May-06-2022, 07:38 PM
Last Post: Extra

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020