@v_program_mist

Как решить ошибку кодировки (Python и MySQLdb)?

На помощь! Начал работать с Python'ом совсем недавно. Написал скрапер, который тащит метаданные с Google Play. Данные забираются и выводятся нормально (т.е. кириллица не сыпется), но при попытке записать эти данные в базу (юзаю модуль MySQLdb), как только встречается запись с кириллицей в поле, выбрасывает следующее:

_mysql_exceptions.OperationalError: (1366, “Incorrect string value: ‘\\xF0\\x9F\\x8D\\x80’ for column ‘title’ at row 1”)


Кодировка базы, таблиц и полей utf8_general_ci.
Связь с базой устанавливаю следующим образом:
conn = MySQLdb.connect('localhost', 'VProgramMist', '1998Vm0000', 'mobasta_history', charset='utf8', init_command='SET NAMES UTF8')


Записываю данные в базу следующим:

sql_str = """INSERT
             INTO history (app_id, title, score, price, free, iap,
             iap_range, size, installs, content_rating,
             date_point, category, collection)
             VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""

        cursor.execute(sql_str, (
            row['app_id'], row['title'], row['score'],
            row['price'], row['free'], row['iap'],
            row['iap_range'], row["size"], row['installs'],
            row['content_rating'][0], datetime.date.today(),
            row['category'][0], row['collection']))


Версия Python 3.7
Версия MySQL - 5.7

P.S. Решил записывать каждую считанную запись. Увидел, что в базу записываются строки с кириллицей. Т.е. что-то он записывает, а на чем-то (например, когда доходит до приложения "Юла"), всё летит к чертям...
  • Вопрос задан
  • 247 просмотров
Пригласить эксперта
Ответы на вопрос 1
netpastor
@netpastor
Python developer
https://mysqlclient.readthedocs.io/user_guide.html...
use_unicode
If True, CHAR and VARCHAR and TEXT columns are returned as Unicode strings, using the configured character set. It is best to set the default encoding in the server configuration, or client configuration (read with read_default_file). If you change the character set after connecting (MySQL-4.1 and later), you’ll need to put the correct character set name in connection.charset.

If False, text-like columns are returned as normal strings, but you can always write Unicode strings.

This must be a keyword parameter.

charset
If present, the connection character set will be changed to this character set, if they are not equal. Support for changing the character set requires MySQL-4.1 and later server; if the server is too old, UnsupportedError will be raised. This option implies use_unicode=True, but you can override this with use_unicode=False, though you probably shouldn’t.

If not present, the default character set is used.

This must be a keyword parameter.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы