# What is a SQL Injection Attack?

A SQL injection attack is something that users can do to you when you're making use of user input in your queries.

Put simply, if you're not careful, your evil users could give you some input that might damage your database or put your data at risk.

Here's how it could happen.

Let's say you've got a query like this one:

SELECT * FROM users WHERE first_name = ?;

But you decide to write it like this in your Python code:

GET_USER = "SELECT * FROM users WHERE first_name = {};"

And then you make use of it like this:

def get_user(username):
    with connection:
        cursor = connection.cursor()
        cursor.execute(GET_USER.format(username))
        return cursor.fetchall()

All seems good! But alas... one of your users decides to try something nasty...

Welcome to the username searching app!

Enter your username:

They try to enter some SQL instead of their username!

Welcome to the username searching app!

Enter your username: ''; DROP TABLE users;

Now when you evaluate the formatted statement, GET_USER.format(username) ends up looking like this:

SELECT * FROM users WHERE first_name = ''; DROP TABLE users;

Guess what's gonna happen!


If you had used ? instead of string formatting, you wouldn't have this problem because sqlite3 will automatically prevent this stuff from happening if you use arguments in the .execute() method, as we've learned.

This would save you:

GET_USER = "SELECT * FROM users WHERE first_name = ?;"


def get_user(username):
    with connection:
        cursor = connection.cursor()
        cursor.execute(GET_USER, (username,))
        return cursor.fetchall()

SQL Injection attacks can happen when developers are not careful. Now you know what they are, so remember to use arguments in sqlite3 and never construct your queries by formatting strings!