Escape single quote character for use in an SQLite query
To escape a single quote ('
) in an SQLite string, utilize two single quotes (''
). So:
This settles the confusion for SQLite, where it would think the end of string has been reached. Remember: Double the fun, double the quotes.
Special characters and literal values in SQLite
Escaping quotes for SQL literals
In SQL statements, literal values enclosed within single quotes often contain '
characters. To keep SQLite from tripping, just double the quote:
It's like saying, "I'm quoting ''inside'' a quote." Inception, SQL-style!
BLOB literals and hexadecimal data
For hexadecimal data, SQLite has BLOB literals. A leading x
or X
followed by single-quoted hex data is the rule:
The X
says, "Here comes some hex!". It's like hex-data-superhero!
Handling NULL values
To insert a NULL value, just use the keyword without the quotes:
NULL, the ghost value. It's there but it's also not there. Balancing the Tao in SQL.
Securing and priming your SQLite queries
Preventing SQL injection
Double escaping quotes is a great step against SQL injection. Better yet, use parameterized queries:
Also, sanitize user input before constructing your SQL queries. SQL: "Cleanliness is next to godliness."
Handling DBNull and object conversion
With languages such as C# or Java, ensure DBNull values are correctly converted. Because NULL in SQL is like a hole in a donut - you don't see it, but it's still there!
Pre-processing in client languages
In Python or JavaScript, replace single quotes ('
) before building your SQL query:
But remember, it's not a substitute for prepared statements. Like a cherry on top - nice, but not the cake!
Diverse scenarios and problems you may encounter
Correctly escaping within strings
Account for all places where single quotes might appear:
Beware of non-standard escape sequences
Unlike other databases, SQLite doesn't play well with backslash \
escapes. So remember, backslashes are to SQLite what kryptonite is to Superman!
Pasting text into SQLite
When copying text into an SQLite query, beware of curly quotes. Only straight quotes get a pass:
Streamlining complex queries
For long or complex queries, use concatenated strings or text editors with SQL support to do the heavy lifting:
Was this article helpful?