Last active
February 12, 2020 18:48
-
-
Save realFranco/d842f26d300209adf4b64cdd7984d04c to your computer and use it in GitHub Desktop.
python's SQLite client.
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
""" | |
SQL client to create or consuting a DB. | |
Dev: Franco Gil. | |
""" | |
import os | |
import json | |
from time import gmtime, strftime | |
import sqlite3 | |
class dbMaker(): | |
def __init__(self, name, table_name=""): | |
""" | |
@param name string, name of the db | |
need to include the extension '.db' | |
name = "MyDB.db' | |
""" | |
self.name = name | |
self.tableName = table_name | |
self.row_dict = False | |
def connect(self, _dict=False): | |
self.conn = sqlite3.connect(self.name) | |
if _dict: | |
self.conn.row_factory = sqlite3.Row | |
self.row_dict = _dict | |
self.c = self.conn.cursor() | |
def setName(self, name): | |
"""Set another name for a DB | |
""" | |
self.name = name | |
def setTableName(self, name:str): | |
"""Set another name for a Table | |
""" | |
self.tableName = name | |
def executeLine(self, sourceLine): | |
"""Executing a string with a valid SQL syntax | |
""" | |
self.c.execute(sourceLine) | |
self.commit() | |
def commit(self): | |
"""Commited the changes maked into the | |
DataBase | |
""" | |
self.conn.commit() | |
def close(self): | |
""" Close the connection on the current cursor. | |
""" | |
self.conn.close() | |
def insertion(self, row, ParamtableName): | |
"""Executing a insertion in the DB. | |
Using a try/except to catch duplicates rows. | |
output: Boolean | |
True: Succesfull insertion | |
False: Row exist in the Table, not gonna be inserted. | |
""" | |
out = True | |
self.tableName = ParamtableName | |
try: | |
line = "INSERT INTO {} VALUES ({});".format( | |
self.tableName, | |
row | |
) | |
print(line) | |
self.c.execute(line) | |
self.commit() | |
except (sqlite3.IntegrityError, sqlite3.OperationalError): | |
out = False | |
return out | |
def execute_script(self, script_route): | |
qry = open(script_route, 'r').read() | |
self.c.executescript(qry) | |
def selectAll(self, query): | |
"""Consult the database. | |
Execute a query line with a SQL valid syntax. | |
This method will allow the return of the rows in dict containers. | |
@query Str; SQL line of code. | |
""" | |
print(query) | |
out = self.c.execute(query).fetchall() | |
if self.row_dict: | |
out = [dict(_) for _ in out] | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment