abstrait:sqlite3本身并沒有像pymysql一樣原生提供字典形式的游標(biāo)。cursor = conn.cursor(pymysql.cursors.DictCursor)但官方文檔里已經(jīng)有預(yù)留了相應(yīng)的實(shí)現(xiàn)方案。def dict_factory(cursor, row): d = {} for&nb
sqlite3本身并沒有像pymysql一樣原生提供字典形式的游標(biāo)。
cursor = conn.cursor(pymysql.cursors.DictCursor)
但官方文檔里已經(jīng)有預(yù)留了相應(yīng)的實(shí)現(xiàn)方案。
def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
使用這個(gè)函數(shù)代替conn.raw_factory屬性即可。
con = sqlite3.connect(":memory:") #打開在內(nèi)存里的數(shù)據(jù)庫 con.row_factory = dict_factory cur = con.cursor() cur.execute("SELECT 1 as a") print cur.fetchone()["a"]
更多關(guān)于Python Sqlite3以字典形式返回查詢結(jié)果的實(shí)現(xiàn)方法請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!