OSDN Git Service

add database-interface module
authorhylom <hylom@mbwhite.local>
Mon, 31 May 2010 11:29:19 +0000 (20:29 +0900)
committerhylom <hylom@mbwhite.local>
Mon, 31 May 2010 11:29:19 +0000 (20:29 +0900)
databases.py [new file with mode: 0755]

diff --git a/databases.py b/databases.py
new file mode 100755 (executable)
index 0000000..5b3588e
--- /dev/null
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+
+import sqlite3
+import sys
+import getopt
+import os.path
+
+class HatebuDB(object):
+    "Hatena Bookmark Counts Database"
+    DB_FILE = "database/hatebu_dat"
+
+    def __init__(self):
+        self.con = None
+        self.cur = None
+
+    def create_table(self):
+        con = sqlite3.connect(self.DB_FILE)
+        cur = con.cursor()
+
+        cur.execute("""
+          create table count (
+            sid text,
+            count int);""")
+        con.commit()
+        cur.close()
+        con.close()
+
+    def __enter__(self):
+        self.con = sqlite3.connect(self.DB_FILE)
+        self.cur = self.con.cursor()
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        if exc_type:
+            self.con = None
+            self.cur = None
+            return False
+        self.con.commit()
+        self.cur.close()
+        self.con.close()
+        self.con = None
+        self.cur = None
+        return True
+
+
+    def add(self, sid, count):
+        d = dict(sid=sid,
+                 count=count)
+
+        try:
+            self.cur.execute("""insert into count ( sid, count )
+                           values ( :sid, :count );""", d)
+        except sqlite3.IntegrityError:
+            self.cur.execute("""update count set sid = :sid, count = :count
+                           where sid = :sid;""", d)
+
+    def get_count(self, sid):
+        con = sqlite3.connect(self.DB_FILE)
+        cur = con.cursor()
+        cur.execute("""select count from count where sid = ?;""", (sid,))
+        count = cur.fetchone()[0]
+        cur.close()
+        con.close()
+        return count
+        
+def main():
+    usage = "%s [-c]" % sys.argv[0]
+    (optlist, args) = getopt.getopt(sys.argv[1:], "c")
+
+    db = HatebuDB()
+    if ('-c', '') in optlist:
+        # create database
+        db.create_table()
+        return
+    else:
+        print usage
+
+if __name__ == '__main__':
+    main()