119

What could be causing this error when I try to insert a foreign character into the database?

>>UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in position 0: ordinal not in range(256)

And how do I resolve it?

Thanks!

ensnare
  • 40,069
  • 64
  • 158
  • 224

12 Answers12

101

I ran into this same issue when using the Python MySQLdb module. Since MySQL will let you store just about any binary data you want in a text field regardless of character set, I found my solution here:

Using UTF8 with Python MySQLdb

Edit: Quote from the above URL to satisfy the request in the first comment...

"UnicodeEncodeError:'latin-1' codec can't encode character ..."

This is because MySQLdb normally tries to encode everythin to latin-1. This can be fixed by executing the following commands right after you've etablished the connection:

db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')

"db" is the result of MySQLdb.connect(), and "dbc" is the result of db.cursor().

Nick
  • 3,172
  • 3
  • 37
  • 49
Nick
  • 1,270
  • 1
  • 9
  • 8
80

Character U+201C Left Double Quotation Mark is not present in the Latin-1 (ISO-8859-1) encoding.

It is present in code page 1252 (Western European). This is a Windows-specific encoding that is based on ISO-8859-1 but which puts extra characters into the range 0x80-0x9F. Code page 1252 is often confused with ISO-8859-1, and it's an annoying but now-standard web browser behaviour that if you serve your pages as ISO-8859-1, the browser will treat them as cp1252 instead. However, they really are two distinct encodings:

>>> u'He said \u201CHello\u201D'.encode('iso-8859-1')
UnicodeEncodeError
>>> u'He said \u201CHello\u201D'.encode('cp1252')
'He said \x93Hello\x94'

If you are using your database only as a byte store, you can use cp1252 to encode and other characters present in the Windows Western code page. But still other Unicode characters which are not present in cp1252 will cause errors.

You can use encode(..., 'ignore') to suppress the errors by getting rid of the characters, but really in this century you should be using UTF-8 in both your database and your pages. This encoding allows any character to be used. You should also ideally tell MySQL you are using UTF-8 strings (by setting the database connection and the collation on string columns), so it can get case-insensitive comparison and sorting right.

bobince
  • 528,062
  • 107
  • 651
  • 834
  • 1
    Isn't `cp1252` a strict superset of ISO-8859-1? I.e. when browsers receive an ISO-8859-1 page, they can render it as if it was CP1252 because there won't be any characters from the range `0x80-0x9F` anyway. – MSalters Oct 15 '10 at 14:45
  • 3
    No, the bytes 0x80–0x9F do have real assignments in ISO-8859-1, which are overridden by cp1252's additions so it's not a superset. They map exactly to the Unicode characters U+0080–U+009F, which are a selection of control characters. They're control characters that aren't used very much which is why browsers got away with it, but it's annoying when you are trying to convert a sequences of bytes-as-Unicode. – bobince Oct 15 '10 at 15:03
  • The only time that I've ever seen characters in the range U+0080-U+009F in a file encoded as ISO-8859-1 or UTF-8 resulted from some clown concatenating a bunch of files some of which were encoded in cp850 and then transcoding the resultant mess from "latin1" to UTF-8. The draft HTML5 spec is considering sanctifying that very practical browser behaviour (and a whole bunch of similar cases) -- see http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#character-encodings-0 – John Machin Oct 18 '10 at 23:39
24

The best solution is

  1. set mysql's charset to 'utf-8'
  2. do like this comment(add use_unicode=True and charset="utf8")

    db = MySQLdb.connect(host="localhost", user = "root", passwd = "", db = "testdb", use_unicode=True, charset="utf8") – KyungHoon Kim Mar 13 '14 at 17:04

detail see :

class Connection(_mysql.connection):

    """MySQL Database Connection Object"""

    default_cursor = cursors.Cursor

    def __init__(self, *args, **kwargs):
        """

        Create a connection to the database. It is strongly recommended
        that you only use keyword parameters. Consult the MySQL C API
        documentation for more information.

        host
          string, host to connect

        user
          string, user to connect as

        passwd
          string, password to use

        db
          string, database to use

        port
          integer, TCP/IP port to connect to

        unix_socket
          string, location of unix_socket to use

        conv
          conversion dictionary, see MySQLdb.converters

        connect_timeout
          number of seconds to wait before the connection attempt
          fails.

        compress
          if set, compression is enabled

        named_pipe
          if set, a named pipe is used to connect (Windows only)

        init_command
          command which is run once the connection is created

        read_default_file
          file from which default client values are read

        read_default_group
          configuration group to use from the default file

        cursorclass
          class object, used to create cursors (keyword only)

        use_unicode
          If True, text-like columns are returned as unicode objects
          using the connection's character set.  Otherwise, text-like
          columns are returned as strings.  columns are returned as
          normal strings. Unicode objects will always be encoded to
          the connection's character set regardless of this setting.

        charset
          If supplied, the connection character set will be changed
          to this character set (MySQL-4.1 and newer). This implies
          use_unicode=True.

        sql_mode
          If supplied, the session SQL mode will be changed to this
          setting (MySQL-4.1 and newer). For more details and legal
          values, see the MySQL documentation.

        client_flag
          integer, flags to use or 0
          (see MySQL docs or constants/CLIENTS.py)

        ssl
          dictionary or mapping, contains SSL connection parameters;
          see the MySQL documentation for more details
          (mysql_ssl_set()).  If this is set, and the client does not
          support SSL, NotSupportedError will be raised.

        local_infile
          integer, non-zero enables LOAD LOCAL INFILE; zero disables

        autocommit
          If False (default), autocommit is disabled.
          If True, autocommit is enabled.
          If None, autocommit isn't set and server default is used.

        There are a number of undocumented, non-standard methods. See the
        documentation for the MySQL C API for some hints on what they do.

        """
Cheney
  • 960
  • 8
  • 23
  • 2
    This answer needs more upvotes. This is a clean solution, clearing the application layer of unnecessary encoding overheads. – yeaske Mar 08 '18 at 17:09
  • Great! This is exactly what I was looking for – Geek Jun 10 '18 at 23:29
  • Additionally, we'd better to set `utf8mb4` for mysql if having `emoji` .etc, refer to [what-is-the-difference-between-utf8mb4-and-utf8-charsets-in-mysql](https://stackoverflow.com/questions/30074492/what-is-the-difference-between-utf8mb4-and-utf8-charsets-in-mysql) – Cheney Jun 26 '18 at 03:37
21

I hope your database is at least UTF-8. Then you will need to run yourstring.encode('utf-8') before you try putting it into the database.

Scott Bartell
  • 2,801
  • 3
  • 24
  • 36
knitti
  • 6,817
  • 31
  • 42
5

Use the below snippet to convert the text from Latin to English

import unicodedata
def strip_accents(text):
    return "".join(char for char in
                   unicodedata.normalize('NFKD', text)
                   if unicodedata.category(char) != 'Mn')

strip_accents('áéíñóúü')

output:

'aeinouu'

kenlukas
  • 3,616
  • 9
  • 25
  • 36
Uday Allu
  • 77
  • 1
  • 3
4

You are trying to store a Unicode codepoint \u201c using an encoding ISO-8859-1 / Latin-1 that can't describe that codepoint. Either you might need to alter the database to use utf-8, and store the string data using an appropriate encoding, or you might want to sanitise your inputs prior to storing the content; i.e. using something like Sam Ruby's excellent i18n guide. That talks about the issues that windows-1252 can cause, and suggests how to process it, plus links to sample code!

jabley
  • 2,212
  • 2
  • 19
  • 23
3

SQLAlchemy users can simply specify their field as convert_unicode=True.

Example: sqlalchemy.String(1000, convert_unicode=True)

SQLAlchemy will simply accept unicode objects and return them back, handling the encoding itself.

Docs

mgojohn
  • 881
  • 9
  • 15
1

Latin-1 (aka ISO 8859-1) is a single octet character encoding scheme, and you can't fit \u201c () into a byte.

Did you mean to use UTF-8 encoding?

msw
  • 42,753
  • 9
  • 87
  • 112
  • 1
    Latin-1 encodes _specific_ Unicode characters, just not that one. It doesn't matter if \u201c can't fit in a byte. windows-1252 is a single octet encoding scheme also, and _does_ including \u201c. – Mark Tolonen Oct 15 '10 at 18:21
  • cp1253 (aka windows-1253) is also a single octet character encoding scheme, and yet `\u0391` fits fine in a byte (specifically, byte 193). You *might* want to take a look at [that](http://stackoverflow.com/questions/368805/python-unicodedecodeerror-am-i-misunderstanding-encode/370199#370199); people have found it helpful. – tzot Oct 15 '10 at 19:30
  • Unicode incorporates Latin-1/cp1253 glyphs in as 16-bit codepoints. I'm surprised that the comments seem to be claiming the converse. – msw Oct 16 '10 at 04:11
  • @msw You misunderstand, and make false claims. Unicode wasn't 16-bit even in 2010. The comments talk about 8-bit encodings which cover some specific Unicode code points outside the Latin-1 repertoire. Those encodings are still 8-bit, just like Latin-1, but contain different "extended" characters. (I hate that term, but it's hopefully clear in this context.) – tripleee Aug 28 '22 at 19:12
1

UnicodeEncodeError: 'latin-1' codec can't encode character '\u2013' in position 106: ordinal not in range(256)

Solution 1: \u2013 - google the character meaning to identify what character actually causing this error, Then you can replace that specific character, in the string with some other character, that's part of the encoding you are using.

Solution 2: Change the string encoding to some encoding which includes all the character of your string. and then you can print that string, it will work just fine.

below code is used to change encoding of the string , borrowed from @bobince

 u'He said \u201CHello\u201D'.encode('cp1252')
Arpan Saini
  • 4,623
  • 1
  • 42
  • 50
0

The latest version of mysql.connector has only

db.set_charset_collation('utf8', 'utf8_general_ci')

and NOT

db.set_character_set('utf8') //This feature is not available
Mnyikka
  • 1,223
  • 17
  • 12
0

I ran into the same problem when I was using PyMySQL. I checked this package version, it's 0.7.9. Then I uninstall it and reinstall PyMySQL-1.0.2, the issue is solved.

pip uninstall PyMySQL
pip install PyMySQL
Sincere_Ye
  • 21
  • 2
-5

Python: You will need to add # - * - coding: UTF-8 - * - (remove the spaces around * ) to the first line of the python file. and then add the following to the text to encode: .encode('ascii', 'xmlcharrefreplace'). This will replace all the unicode characters with it's ASCII equivalent.

nids
  • 925
  • 2
  • 11
  • 16