Last active
November 7, 2023 18:59
-
-
Save itrewm/03b8f978ec2459cbf2ce7c0329625c85 to your computer and use it in GitHub Desktop.
Object-oriented SQLite database
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 pathlib | |
import sqlite3 | |
import logging | |
PATH = pathlib.Path(__file__).parent.resolve() | |
class Database: | |
def __init__(self) -> None: | |
self._connect() | |
self.make_users_table() | |
def _connect(self) -> None: | |
try: | |
self.conn = sqlite3.connect(f"{PATH}/database.db", check_same_thread=False) | |
self._cur = self.conn.cursor() | |
except Exception as e: | |
logging.error('Database connection failed: ' + str(e)) | |
exit() | |
def make_table(self) -> None: | |
try: | |
self._cur.execute( | |
"""CREATE TABLE IF NOT EXISTS TABLE_NAME( | |
column1 INTEGER, | |
column2 INTEGER); | |
""") | |
self.conn.commit() | |
except Exception as e: | |
logging.error('Table creation failed: ' + str(e)) | |
def insert_data(self, data1, data2) -> bool: | |
try: | |
self._cur.execute( | |
"INSERT INTO TABLE_NAME VALUES(? ,?, ?);", [data1, data2] | |
) | |
self.conn.commit() | |
return True | |
except Exception as e: | |
logging.error('insert user data failed: ' + str(e)) | |
def select_data(self, user_id): | |
query = "SELECT column1 FROM TABLE_NAME WHERE column2 = ?" | |
self._cur.execute(query, [user_id]) | |
rows = self._cur.fetchone() | |
self.conn.commit() | |
return rows[0] | |
def update_data(self, user_id): | |
query = "UPDATE TABLE_NAME SET column1 == ? WHERE column2 = ?;" | |
self._cur.execute( | |
query, [user_id] | |
) | |
self.conn.commit() | |
return True | |
db = Database() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment