Last active
January 1, 2016 04:39
-
-
Save liuweiathust/8093360 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlite3 | |
class DummyDict(object): | |
def __init__(self, database="database.db"): | |
self.database = sqlite3.connect(database) | |
self.db = self.database.cursor() | |
self.db.execute("DROP TABLE IF EXISTS test") | |
self.db.execute("CREATE TABLE test (name VARCHAR(255) PRIMARY KEY, content VARCHAR(255))") | |
def __getitem__(self, key): | |
self.db.execute("SELECT content FROM test WHERE name = ?", (key, )) | |
return self.db.fetchone()[0] | |
def __setitem__(self, key, value): | |
if key in self: | |
self.db.execute("UPDATE test SET content = ? WHERE name = ?", (value, key)) | |
else: | |
self.db.execute("INSERT INTO test VALUES(?, ?)", (key, value)) | |
def __contains__(self, key): | |
self.db.execute("SELECT * FROM test where name = ?", (key, )) | |
return self.db.fetchone() != None | |
def close(self): | |
self.db.close() | |
self.database.close() | |
d = DummyDict("example.database.db") | |
d["a"] = "hello world" | |
print "a" in d | |
print "b" in d | |
print d["a"] | |
d.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment