Skip to main content
 首页 » 编程设计

python之问题 cursor.description 从不返回列名称中的方括号(python 2.7 + sqlite3)别名

2025年02月15日11kenshinobiy

我正在尝试使用 cursor.description 来获取 sqlite3 列名,但当列名包含方括号时,我尝试的任何操作都不起作用。在看https://docs.python.org/2/library/sqlite3.html ,似乎我可以使用 sqlite3.connect() 的 detect_types 参数,但这似乎没有任何效果。这是我尝试过的:

import sqlite3 
import sys 
 
# tried using detect_types=0, sqlite3.PARSE_COLNAMES, or sqlite3.PARSE_DECLTYPES) 
# all 3 values yield the same result 
conn = sqlite3.connect(':memory:', detect_types=0) 
cur = conn.cursor() 
cur.execute('select 1 as "H[ello"') 
 
for x in cur.description: 
    sys.stderr.write("should write H[ello, but only writes: " + x[0]) 
    # output: 
    #   should write H[ello, but only writes: H 

请您参考如下方法:

[ 似乎是一个特例 - 它是filtered by the sqlite3 module while building a column name for the cursor description :

PyObject* _pysqlite_build_column_name(const char* colname) 
{ 
    const char* pos; 
 
    if (!colname) { 
        Py_RETURN_NONE; 
    } 
 
    for (pos = colname;; pos++) { 
        if (*pos == 0 || *pos == '[') { 
            if ((*pos == '[') && (pos > colname) && (*(pos-1) == ' ')) { 
                pos--; 
            } 
            return PyUnicode_FromStringAndSize(colname, pos - colname); 
        } 
    } 
} 

虽然我不确定为什么 - 可能与与 MS Access 的兼容性有关。