Created
September 24, 2017 06:16
-
-
Save mzmmoazam/92d620c546541abdd6ff9da260c907a7 to your computer and use it in GitHub Desktop.
This is to simple the usage of database in any application and create a readable and modular script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlite3 | |
class database(object): | |
def __init__(self): | |
self.filename = "help.db" | |
self.table = "help_data" | |
self.sql_do('create table if not exists '+self.table+' ( key TEXT,data TEXT)') | |
def sql_do(self, sql, *params): | |
self._db.execute(sql, params) | |
self._db.commit() | |
def insert(self, row): | |
self._db.execute('insert into {} (key, data) values (?, ?)'.format(self._table), | |
(row['key'], row['data'])) | |
self._db.commit() | |
def retrieve(self, key): | |
cursor = self._db.execute('select key,data from {} where key = ?'.format(self._table), (key,)) | |
return dict(cursor.fetchone()) | |
def update(self, row): | |
self._db.execute( | |
'update {} set data=? where key = ?'.format(self._table), | |
(row['data'],row['key'])) | |
self._db.commit() | |
def delete(self, key): | |
self._db.execute('delete from {} where key = ?'.format(self._table), (key,)) | |
self._db.commit() | |
def __iter__(self): | |
cursor = self._db.execute('select * from {} '.format(self._table)) | |
for row in cursor: | |
yield dict(row) | |
@property | |
def filename(self): | |
return self._filename | |
@filename.setter | |
def filename(self, fn): | |
self._filename = fn | |
self._db = sqlite3.connect(fn,check_same_thread=False) | |
print(self._db) | |
self._db.row_factory = sqlite3.Row | |
@filename.deleter | |
def filename(self): | |
self.close() | |
@property | |
def table(self): | |
return self._table | |
@table.setter | |
def table(self, t): | |
self._table = t | |
def close(self): | |
self._db.close() | |
if __name__ == '__main__': | |
d=database() | |
d.insert({"key":"list","data":"some info regarding list"}) | |
for i in d: | |
print(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment