[Python-checkins] r66323 - sandbox/trunk/dbm_sqlite/Lib/dbm/sqlite.py
skip.montanaro
python-checkins at python.org
Tue Sep 9 04:25:09 CEST 2008
Author: skip.montanaro
Date: Tue Sep 9 04:25:08 2008
New Revision: 66323
Log:
Minimize duplicate SQL. Get rid of cursor closes (apparently not needed).
Modified:
sandbox/trunk/dbm_sqlite/Lib/dbm/sqlite.py
Modified: sandbox/trunk/dbm_sqlite/Lib/dbm/sqlite.py
==============================================================================
--- sandbox/trunk/dbm_sqlite/Lib/dbm/sqlite.py (original)
+++ sandbox/trunk/dbm_sqlite/Lib/dbm/sqlite.py Tue Sep 9 04:25:08 2008
@@ -25,40 +25,29 @@
try:
c.execute("select count(key) from dict")
except sqlite3.OperationalError:
- c.execute("""create table dict (key text, value text)""")
+ c.execute("create table dict (key blob primary key, value blob)")
self._conn.commit()
- finally:
- c.close()
def __getitem__(self, key):
c = self._conn.cursor()
- try:
- c.execute("select value from dict"
- " where key = ?", (key,))
- rows = list(c)
- if not rows:
- raise KeyError(key)
- return rows[0][0]
- finally:
- c.close()
+ c.execute("select value from dict"
+ " where key = ?", (key,))
+ rows = list(c)
+ if not rows:
+ raise KeyError(key)
+ return rows[0][0]
def __setitem__(self, key, val):
- del self[key]
c = self._conn.cursor()
- try:
- c.execute("insert into dict"
- " (key, value) values (?, ?)", (key, val))
- self._conn.commit()
- finally:
- c.close()
+ c.execute("replace into dict (key, value) values (?, ?)", (key, val))
+ self._conn.commit()
def __delitem__(self, key):
+ # Complain if it's not there.
+ self.__getitem__(key)
c = self._conn.cursor()
- try:
- c.execute("delete from dict where key = ?", (key,))
- self._conn.commit()
- finally:
- c.close()
+ c.execute("delete from dict where key = ?", (key,))
+ self._conn.commit()
def iterkeys(self):
c = self._conn.cursor()
@@ -77,13 +66,12 @@
return (e for e in c)
def __contains__(self, key):
- c = self._conn.cursor()
try:
- c.execute("select value from dict"
- " where key = ?", (key,))
- return not not list(c)
- finally:
- c.close()
+ self.__getitem__(key)
+ except KeyError:
+ return False
+ else:
+ return True
def keys(self):
return list(self.iterkeys())
@@ -96,11 +84,8 @@
def __len__(self):
c = self._conn.cursor()
- try:
- c.execute("select count(key) from dict")
- return int(list(c)[0])
- finally:
- c.close()
+ c.execute("select count(key) from dict")
+ return int(list(c)[0])
def close(self):
if self._conn is not None:
More information about the Python-checkins
mailing list