Last active
December 16, 2019 16:55
-
-
Save BideoWego/8fb1bcfc4d568c203d54 to your computer and use it in GitHub Desktop.
Simple Python Model class for use with SQLite3
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 Model: | |
def __init__(self, db, table): | |
self.db = db | |
self.table = table | |
self.connection = sqlite3.connect(db + '.db') | |
self.connection.row_factory = sqlite3.Row | |
def create(self, row): | |
bindings = '(' | |
keys = '(' | |
values = [] | |
i = 0 | |
for key, value in row.items(): | |
bindings += '?' | |
keys += key | |
values.append(value) | |
i += 1 | |
if i != (len(row)): | |
bindings += ', ' | |
keys += ', ' | |
bindings += ')' | |
keys += ')' | |
sql = 'INSERT INTO {} {} VALUES {}'.format(self.table, keys, bindings) | |
print(sql, values) | |
self.connection.execute(sql, values) | |
self.connection.commit() | |
def read(self): | |
sql = 'SELECT * FROM {}'.format(self.table) | |
print(sql) | |
cursor = self.connection.execute(sql) | |
rows = [] | |
for row in cursor: | |
print(dict(row)) | |
rows.append(row) | |
return rows | |
def update(self, row, where): | |
keys = '' | |
values = [] | |
i = 0 | |
for key, value in row.items(): | |
keys += key + ' = ?' | |
values.append(value) | |
i += 1 | |
if i != len(row): | |
keys += ', ' | |
sql = 'UPDATE {} SET {} WHERE {} = {}'.format(self.table, keys, where['key'], where['value']) | |
print(sql, values) | |
self.connection.execute(sql, values) | |
self.connection.commit() | |
def delete(self, where): | |
sql = 'DELETE FROM {} WHERE {} = {}'.format(self.table, where['key'], where['value']) | |
print(sql) | |
self.connection.execute(sql) | |
self.connection.commit() | |
def main(): | |
m = Model('test', 'test') | |
m.create(dict(t1='dudez', i1=9876)) | |
m.update(dict(t1='faz', i1=2345), dict(key='i1', value=1234)) | |
m.delete(dict(key='i1', value=4)) | |
print(m.read()) | |
if __name__ == "__main__": main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment