You can easily implement such class.
class DBMap:
def __del__(self):
self.conn.close()
def __init__(self):
self.conn = sqlite3.connect('map.db')
def __getitem__(self, uuid):
val = self.conn.execute(
'select val from m where uuid = ?', (uuid,)
).fetchone()
if val:
return val[0]
else:
raise KeyError
On __init__
, the connection to database is established and it is closed when __del__
eted.
__getitem__
is to implement evaluation of self[key]
. So you can do the following:
dbm = DBMap()
print(dbm['aaa'])
Here is the .schema
I used.
create table m (
uuid TEXT NOT NULL UNIQUE,
val INTEGER
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…