borg-manager/Database.py
George Lacey f6a52ece4d Add query()
- Add query() to query db and return result as list of attributes
- Refactor row_string -> rows in create_table()
- Add method documentation
2016-09-21 20:33:44 +01:00

55 lines
1.7 KiB
Python

import sqlite3
class Database(object):
def __init__(self, path):
self.conn = sqlite3.connect(path)
def __del__(self):
self.conn.close()
def create_table(self, name, row_list):
"""creates table 'name' with rows from 'row_list' if it doesn't exist"""
if self.table_exists(name):
return True
else:
rows = ""
separator = ", "
for i in range(0, len(row_list)):
if i == len(row_list) - 1:
separator = ""
rows += "%s%s" % (row_list[i], separator)
self.conn.execute("CREATE TABLE %s(%s)" % (name, rows))
if self.table_exists(name):
return True
else:
return False
def table_exists(self, name):
"""returns true if table 'name' exists"""
result = self.conn.execute("""SELECT * FROM sqlite_master
WHERE type='table' AND name=?""", (name,))
if result.fetchone() is None:
return False
else:
return True
def insert(self, log_entry, table):
result = self.conn.execute("""INSERT INTO %s(NAME,
FINGERPRINT, START_TIME, DURATION, FILE_COUNT) VALUES(?,?,?,?,?)"""
% table,
(log_entry.name,
log_entry.fingerprint,
log_entry.datetime_string(),
log_entry.duration,
log_entry.file_count))
self.conn.commit()
def query(self, query):
return self.conn.execute(query).fetchall()