1 from pysqlite2
import dbapi2
as sqlite
3 DATABASE_FILE_NAME
= "data.db"
7 Provides an entry point to the database.
11 def __init__(self
, db_path
):
12 self
._connections
= {}
13 self
._db
_path
= db_path
17 f
= open('data/sql/create_01.sql', 'r')
20 return sql
.split("--")
26 # Check if we need init.
27 # TODO: use smarter strategy maybe?
28 result
= self
.query("SELECT COUNT(*) FROM feeds")
30 # DB seems not initialized.
46 print "DB init failed -- %s" % e
50 key
= threading
.currentThread()
51 if not self
._connections
.has_key(key
):
52 self
._connections
[key
] = sqlite
.connect(self
._db
_path
)
53 self
._connections
[key
].row_factory
= sqlite
.Row
55 return self
._connections
[key
]
58 self
._connect
().commit()
60 def query(self
, query
, params
= None):
63 cursor
= self
._connect
()
65 res
= cursor
.execute(query
, params
)
68 def insert(self
, table
, data
):
70 Inserts some data into the database.
72 @param table: a name of the table to insert to
73 @param data: a dictionary where keys are field names and values
74 are field values in the given table
78 cursor
= self
._connect
().cursor()
79 query
= "INSERT INTO %s (%s) VALUES (?%s)" % (table
, ", ".join(data
.keys()),
80 ", ?" * (len(data
.keys()) - 1))
83 cursor
.execute(query
, data
.values())
85 return cursor
.lastrowid
87 def update(self
, table
, id, data
):
89 Updates single row identified by a primary key in the table.
91 @param table: a name of the table to do the update in
92 @param id: primary key of the item to update
93 @param data: a dictionary where keys are field names and values
94 are field values in the given table
98 params
= data
.values()
99 cursor
= self
._connect
().cursor()
100 assignments
= ", ".join([("%s = ?" % field_name
) for field_name
in data
.keys()])
101 query
= "UPDATE %s SET %s WHERE id = ?" % (table
, assignments
)
104 cursor
.execute(query
, params
)
106 return cursor
.lastrowid