Phil_oneil
Phil_oneil

Reputation: 267

How can I insert a Python variable in a sqlite query?

I'm looking for the way to be able to compare what is in a Python variable with something in a SQLite query.

For example:

num = input ("enter a number")
cur.execute("SELECT a.Name,a.Number FROM Ads a WHERE a.Number = (num)")
row = cur.fetchone()
while row:
    print(row) 
    row = cur.fetchone()

The cur.execute line doesn't work. I don't know how to be able to compare content of a Python variable with data in a SQLite database via a SQlite query.

Upvotes: 2

Views: 8194

Answers (1)

Mike Bessonov
Mike Bessonov

Reputation: 686

You put a '?' as a place holder for each Python variable, something like

num = 5
cur.execute("SELECT Name, Number FROM Ads WHERE Number = ?", (num,))

The execute() method expects a sequence as a second argument, since several '?' positional placeholders can be used in the SQL statement.

Upvotes: 5

Related Questions