python cyrillic decode

后端 未结 2 1709
别那么骄傲
别那么骄傲 2021-01-24 17:54

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=\"XX         


        
相关标签:
2条回答
  • 2021-01-24 18:29

    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.

    0 讨论(0)
  • 2021-01-24 18:31

    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
    
    0 讨论(0)
提交回复
热议问题