我的问题是关于如何在查询后关闭“ conn”对象。查询可以很多。
class MusicAPI(object):
def __init__(self):
logger.info("Loading music database ...")
self.conn = sqlite3.connect('data/music.db')
def search_by_artist(self, artist, song=None, genre=None):
assert (artist is not None), "artist must be provided in search_by_artist!"
query = "SELECT * from musicians where artist == '" + artist + "'"
if song is not None:
query += " and song == '" + song + "'"
if genre is not None:
query += " and genre == '" + genre + "'"
results = set()
cursor = self.conn.execute(query)
for row in cursor:
results.add(row[0])
return results
然后我可以使用API进行查询:
class SearchMusic(object):
def name(self):
return "search_music"
def query(self, query_term):
music_api = MusicAPI()
r = music_api.search_by_artist(query_term)
如何正确关闭在 init 函数中创建的“ conn”?