1

I'm trying to print cyrillic chars selected from mysql. Here is my code: content id DB is cp1251

>>> db = MySQLdb.connect(host="localhost", user="XXX", passwd="XXXX" )
>>> cursor = db.cursor()
>>> cursor.execute("""select id,title,cat,text,tags,date from db1.table1;""")
>>> test=cursor.fetchone()
>>> somevar=test[1]
>>> somevar=somevar.decode('utf8')
>>> print somevar
Result: ?????? ?? ????????

Please guide me how to print this correctly. Thx.

asked Apr 9, 2013 at 16:32
2
  • 1
    What does your original string look like? Commented Apr 9, 2013 at 16:37
  • 1
    As @summea points out, adding an example of with a current output (before you try to decode it) would avoid us just guessing what the problem is - and improves your chances of getting a good answer. Commented Apr 9, 2013 at 16:49

2 Answers 2

3

This helped me (got it from here):

db = MySQLdb.connect("localhost", config.db_user, config.db_pwd, config.db_name)
# here's the magic
db.set_character_set("utf8")
dbc = db.cursor()
dbc.execute("SET NAMES utf8;")
dbc.execute("SET CHARACTER SET utf8;")
dbc.execute("SET character_set_connection=utf8;")
# and here goes your SELECT for cyrillic fields
dbc.execute("SELECT id, title, cat, text, tags, date FROM db1.table1;")
# and then you just get the results
test = dbc.fetchone()
somevar = test[1]
print somevar
answered Oct 22, 2015 at 19:25
Sign up to request clarification or add additional context in comments.

Comments

1

try this:

somevar = somevar.decode('cp1251')

If that does not help, try to add charset='cp1251' parameter in MySQLdb.connect and there is use_unicode parameter, maybe you should use it to...


all connect parameter you can find here https://github.com/farcepest/MySQLdb1/blob/master/MySQLdb/connections.py

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.

answered Apr 9, 2013 at 16:36

2 Comments

Hi, thanks for you answer, I tried decode('cp1251'), decode('utf8'), decode('utf-8'), encode('cp1251'), encode('utf8'), encode('utf-8') but without success :( any other ideas ?
database charset is utf, but table charset is cp1251

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.