Last active
December 22, 2024 11:44
-
-
Save GluTbl/356388acaa7986b3a0af01aef79e8a60 to your computer and use it in GitHub Desktop.
SqLite python API #python #sql #sqlite
This file contains hidden or 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 | |
import base64 | |
class SqlideApi(): | |
def __init__(self, dbname, tablename): | |
self.tablename = tablename | |
self.dbname = dbname | |
self.con = None | |
try: | |
self.con = sqlite3.connect(self.dbname) | |
with self.con: | |
cur = self.con.cursor() | |
cur.execute( | |
"CREATE TABLE IF NOT EXISTS " + tablename + "(day TEXT PRIMARY KEY NOT NULL, plan TEXT)") | |
print("Db initiated") | |
except Exception as e: | |
print(e) | |
pass | |
finally: | |
if self.con: | |
self.con.close() | |
def connect(self): | |
self.con = None | |
try: | |
self.con = sqlite3.connect(self.dbname) | |
except: | |
pass | |
def add_data(self, day, plan): | |
########Encode to base 64######### | |
plan = base64.b64encode(plan.encode("UTF-8")).decode("UTF-8") | |
################################## | |
self.connect() | |
if self.con == None: | |
print("Db connection error!") | |
return 0 | |
cur = self.con.cursor() | |
try: | |
print("Trying to added data") | |
cur.execute( | |
"INSERT INTO " + self.tablename + " (day,plan) VALUES('" + day + "','" + plan + "')") | |
self.con.commit() | |
print("Added data") | |
noterr = 1 | |
except Exception as e: | |
try: | |
ex = "UPDATE " + self.tablename + " set plan = ? where day = ?" | |
cur.execute(ex, (plan, day)) | |
# cur.execute(ex, (task+"sfsf", executable+"sadasdsad", data+"adasdsad", mili+"asdsaddad", barcode)) | |
self.con.commit() | |
noterr = 1 | |
except Exception as f: | |
print("Error in adding data") | |
noterr = -1 | |
pass | |
finally: | |
if self.con: | |
self.con.close() | |
finally: | |
if self.con: | |
self.con.close() | |
return noterr | |
def getdata(self, keyname): | |
self.connect() | |
if self.con == None: | |
print("Db connection error!") | |
return False | |
cur = self.con.cursor() | |
cur.execute("SELECT * FROM " + self.tablename + " WHERE day=:day", {"day": keyname}) | |
row = cur.fetchone() | |
self.con.close() | |
if row !=None: | |
return base64.b64decode(row[1].encode("UTF-8")).decode("UTF-8") | |
return None | |
tablenamen = 'Day_Planner' | |
dbname = 'Day_Planner.db' | |
li=SqlideApi(dbname,tablenamen) | |
li.add_data("Wed","Helllo data") | |
print("ddd:",li.getdata("Wed")) | |
li.add_data("Wed","Helllssssso data") | |
print("ddd:",li.getdata("Wed")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment