S
S
Sergey Pavlov2014-07-18 01:46:58
MySQL
Sergey Pavlov, 2014-07-18 01:46:58

How to solve encoding problem in Python+MySQL?

I am just starting to get used to database issues, in parallel with MySQL myself, I am also studying the library for python 2.7 - MySQLdb. The question arose with writing Russian text to a table using python. In MySQL itself, wherever you can put utf-8:

+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+

Here is an example query in Python:
# -*- coding: utf-8 -*-
import MySQLdb
db=MySQLdb.connect(host='localhost',user='root',passwd='qwerty',db='new')
cursor=db.cursor()
name='миша'.encode('utf-8')
cursor.execute("INSERT INTO te(first,second) VALUES('%s','asda')",(name))

The script runs with an error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lorem Ipsum, 2014-07-18
@Pavlov_dog

I did it like this

# Если используется SQLAlchemy, то параметр кодировки можно вставить прямо в параметр
# подключения, например 
create_engine('postgresql+psycopg2://@localhost/test?charset=utf8')

# Если вы используете MySQLdb, то можно передать параметр charset и чтобы точно заработало
# еще и init_command. 
conn = MySQLdb.connect(charset='utf8', init_command='SET NAMES UTF8')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question