Skip to content

Instantly share code, notes, and snippets.

@liuweiathust
Created December 23, 2013 11:19
Show Gist options
  • Save liuweiathust/8095449 to your computer and use it in GitHub Desktop.
Save liuweiathust/8095449 to your computer and use it in GitHub Desktop.
import MySQLdb
class DummyDict(object):
def __init__(self, database="test", user="liuwei", password="123456"):
self.database = MySQLdb.connect("localhost", user, password, 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))")
self.database.commit()
def __getitem__(self, key):
self.db.execute("SELECT content FROM test WHERE name = %s", (key, ))
return self.db.fetchone()[0]
def __setitem__(self, key, value):
if key in self:
self.db.execute("UPDATE test SET content = %s WHERE name = %s", (value, key))
self.database.commit()
else:
self.db.execute("INSERT INTO test VALUES(%s, %s)", (key, value))
self.database.commit()
def __contains__(self, key):
self.db.execute("SELECT * FROM test where name = %s", (key, ))
return self.db.fetchone() != None
def close(self):
self.db.close()
self.database.close()
d = DummyDict("test", "liuwei", "123456")
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