代码块
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]
我的实例
def get_db():
# 连接数据库
db = sqlite3.connect(
'data/test.db',
detect_types=sqlite3.PARSE_DECLTYPES
)
def dict_factory(cursor, row):
# 字典格式
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
# db.row_factory = sqlite3.Row # 返回数据结构类似字典,不加则返回元组
db.row_factory = dict_factory
return db
def select(cs_num, final_time) -> tuple:
# 查询数据时使用,如有则返回元组,无则返回none
db = get_db()
cs_row = db.execute(
'SELECT * FROM cs'
' WHERE cs_num = ? and final_time = ?',
(cs_num, final_time)
).fetchone()
return cs_row