简体   繁体   中英

How do I insert a special character such as ' into MySQL?

I am executing the insert query from a shell script which reads data from multiple files. Some of the data to be inserted contains ' in the text and MySQL keeps giving errors

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Development & Empowerment, Youth Affairs                 
','
Himachal Pradesh                    ' at line 1

This is the actual text: Women's Development & Empowerment, Youth Affairs .

You need to escape the quote, like so:

'Women\'s Development & Empowerment, Youth Affairs'

Note, that if you're generating the SQL statement from a language like PHP, there are functions available to do this for you.

In PHP, for instance, there is mysql_real_escape_string , which takes care of it for you. Note, that prepared statements are to be prefered over this, as it's harder to get those wrong.

See also:

You will have to escape the input strings before passing them to MySql.

The list of escape character s is:

Character   Escape Sequence
\0  An ASCII NUL (0x00) character.
\'  A single quote (“'”) character.
\"  A double quote (“"”) character.
\b  A backspace character.
\n  A newline (linefeed) character.
\r  A carriage return character.
\t  A tab character.
\Z  ASCII 26 (Control-Z). See note following the table.
\\  A backslash (“\”) character.
\%  A “%” character. See note following the table.
\_  A “_” character. See note following the table.

Yo need to escape the ' character with a backslash \\

Women\\'s Development & Empowerment, Youth Affairs

You need to escape your quote. You can do this by doubling it in your insert query; ie use '' rather than '. That is two single quotes rather than a single double quote.

What is the server side languge you using?

there are many methods through which you can escape string , i'll prefer that!

Eg: you can use mysql_escape_string the data you are entering in query so it will automatically escape charecters like " ' "

mysql_escape_string is a php function provided you are using php

I am trying process some files and push some data into mysql. I have written a small shell script for this.

SELECT * FROM tableName WHERE columnName REGEXP '[^a-zA-Z0-9]'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM