ruby sql 19 lines · 3 tabs

SQL injection prevention with unsafe and safe query patterns

Kai Nakamura Apr 2026
3 tabs
# Vulnerable: user input is concatenated directly into SQL.
email = params[:email]
password = params[:password]

sql = "SELECT * FROM users WHERE email = '#{email}' AND password_hash = '#{password}'"
user = ActiveRecord::Base.connection.execute(sql).first
3 files · ruby, sql Explain with highlit

I teach SQL injection by showing the vulnerable pattern first and then replacing it with parameterized queries. The important point is that escaping is not a strategy and string interpolation is not acceptable anywhere user input reaches SQL. I also prefer narrow database roles so a missed injection path cannot become a full database compromise.

Share this code

Here's the card — post it anywhere.

SQL injection prevention with unsafe and safe query patterns — share card
Link copied