A string is a sequence of characters, surrounded by either single quote (`'') or double quote (`"') characters (only the single quote if you run in ANSI mode). Examples:
'a string' "another string"
Within a string, certain sequences have special meaning. Each of these sequences begins with a backslash (`\'), known as the escape character. MySQL recognises the following escape sequences:
\0
NUL
) character.
\'
\"
\b
\n
\r
\t
\z
mysql database < filename
.)
\\
\%
\_
Note that if you use `\%' or `\_' in some string contexts, these will return the strings `\%' and `\_' and not `%' and `_'.
There are several ways to include quotes within a string:
The SELECT
statements shown here demonstrate how quoting and
escaping work:
mysql> SELECT 'hello', '"hello"', '""hello""', 'hel''lo', '\'hello'; +-------+---------+-----------+--------+--------+ | hello | "hello" | ""hello"" | hel'lo | 'hello | +-------+---------+-----------+--------+--------+ mysql> SELECT "hello", "'hello'", "''hello''", "hel""lo", "\"hello"; +-------+---------+-----------+--------+--------+ | hello | 'hello' | ''hello'' | hel"lo | "hello | +-------+---------+-----------+--------+--------+ mysql> SELECT "This\nIs\nFour\nlines"; +--------------------+ | This Is Four lines | +--------------------+
If you want to insert binary data into a string column (such as a
BLOB
), the following characters must be represented by escape
sequences:
NUL
\
'
"
If you write C code, you can use the C API function
mysql_real_escape_string()
to escape characters for the INSERT
statement. See section 9.1.2 C API Function Overview. In Perl, you can use the
quote
method of the DBI
package to convert special
characters to the proper escape sequences. See section 9.5.2 The DBI
Interface.
You should use an escape function on any string that might contain any of the special characters listed above!
Alternatively, many MySQL APIs provide some sort of placeholder capability that allows you to insert special markers into a query string, and then bind data values to them when you issue the query. In this case, the API takes case of escaping special characters in the values for you automatically.
Posted by Hans Luyten on Friday March 21 2003, @5:57am | [Delete] [Edit] |
I encountered some problem with additional characters:
char: ?, replace with \?
char: &, replace with \&
Posted by Michel Piguet on Monday March 24 2003, @9:48am | [Delete] [Edit] |
I have no way found to escape a backslash at the end of a string. (Version 3.23.25)
'Hello \' gives an error
'Hello \\' gives an error too
'Hello \\\'' works, but results in "Hello \'"
As the only way I found to add a blank at the end of the line ('Hello \\ ').
This seems to be a problem.
Posted by [name withheld] on Monday April 21 2003, @6:56pm | [Delete] [Edit] |
I tried select "hello ";
and is able to add a blank to end of line.
Posted by irwilliams on Friday April 25 2003, @6:17am | [Delete] [Edit] |
How do I escape comment characters? i.e. #