我正在尝试使用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
答案 0 :(得分:1)
[
似乎是特殊情况 - 它是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的兼容性有关。