SQLite, python, unicode, and non-utf data

后端 未结 5 637
死守一世寂寞
死守一世寂寞 2020-12-02 05:37

I started by trying to store strings in sqlite using python, and got the message:

sqlite3.ProgrammingError: You must not use 8-bit bytestrings unles

5条回答
  •  北海茫月
    2020-12-02 06:04

    My unicode problems with Python 2.x (Python 2.7.6 to be specific) fixed this:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    from __future__ import unicode_literals
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')
    

    It also solved the error you are mentioning right at the beginning of the post:

    sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless ...

    EDIT

    sys.setdefaultencoding is a dirty hack. Yes, it can solve UTF-8 issues, but everything comes with a price. For more details refer to following links:

    • Why sys.setdefaultencoding() will break code
    • Why we need sys.setdefaultencoding(“utf-8”) in a py script?

提交回复
热议问题