← Back to list

SQL Injection Explained: How Attackers Exploit Your Queries and Learn how to prevent SQL Injection

Non-Medium Members Please Read Here

Rahul Beniwal in Level Up Coding · 2025-11-03 03:08 · 0 claps · 3.6 min read paywalled
#application-security #sql-injection #injection-attacks #web-safety #software-development
Open on Medium ↗
Wiki topics: SAF · Safety & Alignment

SQL Injection Explained: How Attackers Exploit Your Queries and Learn how to prevent SQL Injection

***Non-Medium Members Please Read Here***

Welcome, Everyone. We all write code every day, and we try to make our code clean and pragmatic as much as possible. We feel satisfied and pat our backs at the end of the day; that’s fine and natural, but there are still a lot of things that you really need to know about to make robust and reliable software. Almost all publicly listed companies are very concerned regarding security concerns, which can leave them in hefty ransoms, fines, and tarnish their reputation, and most of the time, their share value also suffers.

Just think about it: a small unintentional mistake can leave your application open to attacks. It doesn’t mean you are a bad software developer; it just means you are missing some fundamental lesson on application security.

In this series, I will be taking you deep into some common attacks, either on the code level or the infrastructure level, to make you more confident in writing secure and robust code.

So let’s start with our first and one of the most popular ones.

SQL Injection Explained

Even in 2025, SQL Injection is still part of the OWASP Top 10 under the injection vulnerability.

Attackers are in love with it because

  • It’s easy to automate.
  • It can expose the entire database with a single request if the attacker is smart.

SQLi ranked 3rd in the top vulnerabilities for 2024. You can check more here.

[embed]CWE Top 25 for 2024: XSS, SQLi, Buffer Overflows Top the List The CWE Top 25 for 2024 ranks software security weaknesses by their presence in reported CVEs in 2023 and 2024. Learn…www.invicti.com

Understanding the SQL Injection Attack

SQL Injection happens when user input gets concatenated into a SQL Query String.

from django.db import connection

def get_user(username, password_hash):
    sql = f"SELECT * FROM user_user WHERE username = '{username}' and password='{password_hash}'"
    print(sql)
    with connection.cursor() as cursor:
        cursor.execute(sql) 
         return cursor.fetchone()

Now, if an attacker enters

get_user("dummyuser@gmail.com' --", "anypasswordnoeffection")

The query becomes:

SELECT * FROM user_user WHERE username = 'dummyuser@gmail.com' --' and password='anypasswordnoeffection'

Great, your system has been compromised, and now the attacker just needs to know the random emails to get access.

(2,
 'dummyu',
 None,
 False,
 'dummyuser@gmail.com',
 'Dummy',
 'User',
 False,
 True,
 datetime.datetime(2025, 6, 24, 7, 14, 29, tzinfo=datetime.timezone.utc),
 'dummyuser@gmail.com',
 False)

How SQL Injection Works (Step by Step)

  • An Application expects a safe input (Like as a username or ID, or password)
  • The application concatenates the input into SQL
  • Attackers inject SQL syntax — quotes, operators, comments (--) to change the query logic.
  • The database executes the modified query
  • And great, you are doomed

Fixing SQL Injection

Use parameterized queries (everywhere)

The single most effective defense is never to build SQL by concatenating user input. Always separate SQL structure from data.

from django.db import connection

     def safe_get_user(username, password_hash):
         sql = "SELECT * FROM user_user WHERE username = %s and password=%s"
         print(sql)
         with connection.cursor() as cursor:
           cursor.execute(sql, (username, password_hash))
[2025-10-29 02:26:17] DEBUG django.db.backends (0.001) SELECT * FROM user_user WHERE username = 'dummyuser@gmail.com --' and password='anypasswordnoeffection'; args=('dummyuser@gmail.com --', 'anypasswordnoeffection'); alias=default

Prefer your framework’s ORM

from django.contrib.auth import authenticate, login

def login_view(request):
    username = request.POST.get("username", "")
    password = request.POST.get("password", "")
    user = authenticate(request, username=username, password=password)
    if user:
        login(request, user)

ORMs exist for a beautiful reason. There are very few software developers at the beginner level who are well-versed in both writing application logic and SQL while following best practices. So ORM does the heavy work for us while exposing a class-based abstraction for tables, that why they are known as Object-Relational Mappers

Never store plaintext passwords — use strong, salted hashing

It is not just related to SQL Injection, but it is the one best practice that must be to. The principle is, not even you, the developer of the application, should know the password of your users to respect their privacy and to make if your DB is under attack, their full account won’t be compromised.

Don’t worry, there exist secure ways to log in as or impersonate to debug some issues.

user = User.objects.get(username="dummyuser@gmail.com")
user.set_password("dmin1912929")
user.save(update_fields=['password'])
UPDATE "user_user" SET "password" = 'pbkdf2_sha256$870000$8erHEZIk1DrrLjA7LSalDe$0jZg+xPcG+4IzITsvLyjHX5Q/gEN7JTlvy/Q1IOx5eo=' WHERE "user_user"."id" = 2;

Protip: Check your framework documentation. There must be some way to hash the password before saving it to the database, instead of you taking care of everything.

Principle of least privilege for DB accounts

It is also one more general principle that should be applied everywhere and can help you minimize the damage caused in case your system is compromised.

  • Web app user: SELECT, INSERT, UPDATE on necessary tables (avoid DROP, ALTER, GRANT).
  • Admin jobs: separate privileged account for migrations and administrative tasks.

Thank you for reading till the end, hope you must have found it helpful, and from next time will make sure your application won’t have at least SQL Injections, and later we will dive into more attack prevention.

Follow Rahul Beniwal for future articles on application security, and don't forget to share your love for the story.

[embed]Before AI Agents Make You a Millionaire, They’ll Make Your Database Cry Friend Link Includedlevelup.gitconnected.com

[embed]From Grade-School Tricks to Karatsuba: How Computers Multiply Big Integers Hello Everyone, Welcome to our ongoing series on where we try to find either the reason behind things or try to solve a…levelup.gitconnected.com


메타데이터
post_id
e8ce4048a677
slug
sql-injection-explained-how-attackers-exploit-your-queries-and-learn-how-to-prevent-sql-injection-e8ce4048a677
url
https://levelup.gitconnected.com/sql-injection-explained-how-attackers-exploit-your-queries-and-learn-how-to-prevent-sql-injection-e8ce4048a677
canonical_url
https://levelup.gitconnected.com/sql-injection-explained-how-attackers-exploit-your-queries-and-learn-how-to-prevent-sql-injection-e8ce4048a677
author_url
https://medium.com/@rahulbeniwal26119
status
ok
fetched_at
2026-06-20 20:29:01