一個普通的選擇,只用三行
def select_column_and_value(db, sql, parameters=()):
execute = db.execute(sql, parameters)
fetch = execute.fetchone()
return {k[0]: v for k, v in list(zip(execute.description, fetch))}
con = sqlite3.connect('/mydatabase.db')
c = con.cursor()
print(select_column_and_value(c, 'SELECT * FROM things WHERE id=?', (id,)))
但是,如果您的查詢返回任何內容,將導致錯誤。在這種情況下...
def select_column_and_value(self, sql, parameters=()):
execute = self.execute(sql, parameters)
fetch = execute.fetchone()
if fetch is None:
return {k[0]: None for k in execute.description}
return {k[0]: v for k, v in list(zip(execute.description, fetch))}
或
def select_column_and_value(self, sql, parameters=()):
execute = self.execute(sql, parameters)
fetch = execute.fetchone()
if fetch is None:
return {}
return {k[0]: v for k, v in list(zip(execute.description, fetch))}
的可能重複[Python的 - MySQLdb的,SQLite的結果作爲字典(HTTP:// stackoverflow.com/questions/4147707/python-mysqldb-sqlite-result-as-dictionary) – vy32 2015-08-22 22:50:09
@ vy32:這個問題是從2010年7月,你鏈接到2010年11月。所以,這是一個愚蠢的。正如人們所期望的那樣,反向評論已經被提上了那個:-) – aneroid 2016-06-07 20:49:16