Python SQL query string formatting
To avoid falling victim to SQL injection, utilize parameterized queries in Python. This involves using placeholders, such as ?
for SQLite and %s
for MySQL. Here's the boilerplate to get you started:
Ensure your DB path is correct, and adjust table/column names as per your schema. Even for single value queries, parameters must be passed as a tuple so the library to handles it correctly.
Avoid SQL injection with f-strings
Use f-strings for easy string interpolation while keeping the SQL queries safe:
Remember - this tactic is useful only when the interpolated strings aren't user input.
SQL string construction using Python's string literal concatenation
Python's string literal concatenation provides a clean way to construct SQL statements, avoiding the need for backslash continuations and enhancing readability:
Enhancing readability with sqlparse
The sqlparse
library in Python helps to reindent and adjust keyword casing for SQL strings, essentially giving them a readability boost:
Using inspect.cleandoc
for whitespace control
Python's inspect.cleandoc
can be leveraged to remove unnecessary whitespace, especially useful for multi-line SQL strings:
With this, you get a neatly formatted SQL query string, which is easier to read and debug.
Organized SQL syntax with a style guide
Following a 'sql style guide' can hugely enhance the readability of your SQL queries. For consistent formatting and structured queries, a popular SQL style guide is available at https://github.com/meadmaker/sql-style-guide.
Secure dynamic SQL execution
Executing dynamic SQL securely can be achieved by avoiding raw string manipulation and leveraging SQLAlchemy's text feature:
Mastering SQL in Python: the cheat sheet
- Parameterize: Prevent SQL injection using parameterized queries.
- Concatenate: Construct queries elegantly using Python's string literal concatenation.
- Format: Use
f-strings
carefully, best for non-user-controlled data. - Clean: Utilize
inspect.cleandoc
to remove extra whitespace. - Indent: Make your SQL pretty and legible with
sqlparse
. - Style: Use a SQL style guide for consistently clear and clean SQL.
- Execute: Perform dynamic SQL securely using
SQLAlchemy's text
.
Was this article helpful?