How SQL Injection Works and How to Prevent It with Safe SQLite Code

This article explains what SQL injection is, demonstrates a vulnerable SQLite example that drops a table using malicious input, shows why the attack works, and provides practical prevention techniques such as using parameterized queries, input validation, unpredictable table names, and regular backups to secure databases.

ITPUB
ITPUB
ITPUB
How SQL Injection Works and How to Prevent It with Safe SQLite Code

What Is SQL Injection?

SQL injection is a common database attack where an attacker inserts malicious SQL keywords into input fields, causing the database engine to execute unintended commands. Because SQL statements combine code and data, untrusted input that contains keywords like SELECT or DROP TABLE can be executed as part of the query.

SQLite Example – Vulnerable Code

import sqlite3
# Connect to database
conn = sqlite3.connect('test.db')
# Create a simple table
conn.executescript('''
DROP TABLE IF EXISTS students;
CREATE TABLE students (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL
);
''')
# Insert normal records
students = ['Paul', 'Tom', 'Tracy', 'Lily']
for name in students:
    query = "INSERT INTO students (name) VALUES ('%s')" % (name)
    conn.executescript(query)
# Show current rows
cursor = conn.execute("SELECT id, name FROM students")
print('IDName')
for row in cursor:
    print('{0}{1}'.format(row[0], row[1]))
conn.close()

Demonstrating the Attack

conn = sqlite3.connect('test.db')
# Insert a malicious string
name = "Robert');DROP TABLE students;--"
query = "INSERT INTO students (name) VALUES ('%s')" % (name)
conn.executescript(query)
# Try to read the table
cursor = conn.execute("SELECT id, name FROM students")
print('IDName')
for row in cursor:
    print('{0}{1}'.format(row[0], row[1]))
conn.close()

Why the Attack Succeeds

The injected value contains the keyword DROP TABLE. The preceding '); terminates the original INSERT statement, so the database interprets the remainder as a separate command that drops the students table. After the table is removed, subsequent queries fail because the table no longer exists.

How to Prevent SQL Injection

Avoid predictable table and column names; obscure schemas make it harder for attackers to guess structure.

Validate input with regular expressions, limiting characters such as quotes, semicolons, and other special symbols.

Use parameterized (prepared) statements so that data and SQL code are sent separately, e.g., INSERT INTO students (name) VALUES (?).

In languages like PHP, escape special characters with functions such as mysql_real_escape_string when parameterized queries are not available.

Maintain regular backups and encrypt sensitive data; backups allow recovery if an injection succeeds.

Safe SQLite Example Using Parameters

conn = sqlite3.connect('test.db')
name = "Robert');DROP TABLE students;--"
query = "INSERT INTO students (name) VALUES (?)"
conn.execute(query, [name])
# Verify the table still exists
cursor = conn.execute("SELECT id, name FROM students")
print('IDName')
for row in cursor:
    print('{0}{1}'.format(row[0], row[1]))
conn.close()

For PHP developers, functions like mysql_real_escape_string can also be used to escape dangerous characters, but parameterized queries remain the most reliable defense.

Source: https://jizhi.im/blog/post/sql_injection_intro

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

SQL injectionSQLiteinput validation
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.