Skip to content

Instantly share code, notes, and snippets.

@kamawanu
Last active February 9, 2022 00:21
Show Gist options
  • Save kamawanu/4502712 to your computer and use it in GitHub Desktop.
Save kamawanu/4502712 to your computer and use it in GitHub Desktop.
wrap sqlite3 as dict
#! https://gist.github.com/4502712
#!/usr/bin/python
#!-*- coding:utf-8 -*-
# https://gist.github.com/4502712
__ALL__ = [
"open",
]
class sqlite3hash(object):
conn = None
createtable = "create table key1s ( key1 , value1 );"
def __init__(self, path1 ):
import sqlite3
import os.path
createtable = os.path.isfile(path1)
self.conn = sqlite3.connect(path1)
try:
self.conn.cursor().execute(self.createtable)
except sqlite3.OperationalError:
pass
def __getitem__(self, key1 ):
crsr = self.conn.cursor()
### import logging
### logging.warn(key1)
crsr.execute( "select value1 from key1s where key1 = '%s'" % key1 )
found = crsr.fetchone()
if found == None: return None
return found[0]
__contains__ = __getitem__
def __setitem__(self, key1, value1 ):
assert type(key1) in ( str, unicode ), type(key1)
assert type(value1) in ( str, unicode )
key1 = str(key1)
value1 = str(value1)
crsr = self.conn.cursor()
sql3str = "insert into key1s ( key1, value1 ) values ( '%s' , '%s' )" % ( key1, value1 )
### import logging;logging.warn(sql3str)
crsr.execute( sql3str )
self.sync()
### return crsr.fetchone()
def sync(self):
self.conn.commit()
open = sqlite3hash
open
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment