Python SQLite:强制执行 UTF-8 编码

Python SQLite: enforce UTF-8 encoding

我正在开发一个跨平台的Python(3.7+)应用程序,我需要依赖SQLite中TEXT列的排序顺序,这意味着TEXT值的比较算法必须基于UTF -8 字节。即使系统编码(sys.getdefaultencoding())不是utf-8.

但是在 sqlite3 module 的文档中我找不到 sqlite3.connect 的编码选项。

而且我读到 sys.setdefaultencoding("utf-8") 的使用是一个丑陋的 hack 并且非常不鼓励(这就是为什么我们需要 reload(sys) 在调用它之前)

那么解决方案是什么?

查看 Python 的 _sqlite/connection.c code, either sqlite3_open_v2 or sqlite3_open is called (depending on a compile flag). And based on sqlite doc,它们都使用 UTF-8 作为默认数据库编码。我仍然不确定“默认”一词的含义,因为它没有提到任何覆盖它的方法!但我看起来 Python 不能用另一种编码打开。

#ifdef SQLITE_OPEN_URI
    Py_BEGIN_ALLOW_THREADS
    rc = sqlite3_open_v2(database, &self->db,
                         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
                         (uri ? SQLITE_OPEN_URI : 0), NULL);
#else
    if (uri) {
        PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
        return -1;
    }
    Py_BEGIN_ALLOW_THREADS
    rc = sqlite3_open(database, &self->db);
#endif