R
R
ramazan2015-07-14 12:09:01
MySQL
ramazan, 2015-07-14 12:09:01

Why are Cyrillic strings incorrectly written to the database?

Creating a table:
mysql> create table names (name text);
Python 2:

# -*- coding: utf-8 -*-
import MySQLdb

db = MySQLdb.connect('localhost', msql_user_name, msql_user_pass, 'vstat')
cursor = db.cursor()
insert = "INSERT INTO names (name) VALUES ('%s')" % 'абв'
cursor.execute(insert)
db.commit()
db.close()

mysql> SELECT * FROM names;
+--------------+
| name         |
+--------------+
| абв       |
+--------------+

When adding:
db.set_character_set('utf8')
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8')

An error is thrown:
Warning: Incorrect string value: '\xD0\xB0\xD0\xB1\xD0\xB2' for column 'name' at row 1
  cursor.execute(insert)

and the output is this:
mysql> SELECT * FROM names;
+------+
| name |
+------+
| ???  |
+------+

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
Roman, 2015-07-14
@voiceofnoise

Look at the encoding of the table itself

SELECT CHARACTER_SET_NAME, COLLATION_NAME
FROM information_schema.columns
WHERE table_name =  'name'

And perhaps in insert before 'abc' it makes sense to try to put u

R
Rsa97, 2015-07-14
@Rsa97

Properties CHARACTER SET for base, table, column.
Server default encoding.
SET NAMES UTF8 after connect.

S
sim3x, 2015-07-14
@sim3x

python2

insert_query = u"INSERT INTO names (name) VALUES ('%s')"
cur.execute(insert_query, u'абв')

https://dev.mysql.com/doc/connector-python/en/conn...

V
Vadim Shandrinov, 2015-07-14
@suguby

You need to recreate the database:
CREATE DATABASE `##DATABASENAME##` /*!40100 DEFAULT CHARACTER SET utf8 */;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question