liveBook · Manning

SQL injection

As explained in Build Python Web Apps with Streamlit

SQL injection is a security vulnerability in which attacker-controlled input alters a database statement to execute unintended SQL commands.

SQL injection occurs when attacker-controlled input changes a database statement and can make it run harmful commands. Keep query structure separate from user input: execute SQLAlchemy’s text(query) with a params dictionary instead of concatenating input into the SQL string. section 8.2.5

Listing 8.1 The Database class
import streamlit as st
from sqlalchemy import text

class Database:
  def __init__(self):
    self.conn = st.connection("haikuconn", type="sql")

  def execute_query(self, query, params={}, write=False):
    with self.conn.session as session:
      try:
        result = session.execute(text(query), params)
        if write:
          session.commit()
        return result.fetchall()
      except Exception:
        if write:
          session.rollback()
        raise

See how the Database class executes queries with text(query) and params, and handles write transactions. section 8.2.5

How Build Python Web Apps with Streamlit covers it

How deep it goes
Defines the risk and explains parameter separation, but does not detail attack techniques or testing.
Examples
Shows a Database class using text(query) and params, alongside a SELECT query for Alice’s haikus.
What you can do after
Apply SQLAlchemy’s text() and params to keep user input separate from SQL structure.
How it connects
Connects SQL injection prevention to SQLAlchemy and parameterized queries.

Also explained in

Compare how 9 books explain SQL injection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.