세 줄만 사용하는 일반적인 대안
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))}