SQLite Injection
What is SQL Injection?
SQL injection is a way to attack a program that builds SQL statements from user input. The attacker types SQL code into an input field, and the code becomes a part of your statement.
An Example
Here is Python code that builds an SQL statement with text from the user. Never do this:
user_id = input("Customer id: ")
sql = "SELECT * FROM Customers WHERE CustomerID = " + user_id
cur.execute(sql)
If the user types 105 OR 1=1, the statement becomes:
1=1 is always true, so the statement returns all the customers, not just one. An attacker can use the same trick to read, change or delete any data.
Use Parameters
The safe way is to use parameters. Write a ? in the statement, and give the values separately. SQLite then treats the value only as data, never as SQL code:
user_id = input("Customer id: ")
cur.execute(
"SELECT * FROM Customers WHERE CustomerID = ?",
(user_id,)
)
You can also use named parameters, like :id:
cur.execute(
"SELECT * FROM Customers WHERE CustomerID = :id",
{"id": user_id}
)
All programming languages that work with SQLite have parameters. Always use them for values that come from users.