Created
April 16, 2023 05:24
-
-
Save lazuee/5ef4ac842021d1ed7d9363fadaf143ba to your computer and use it in GitHub Desktop.
SQLite3 Database for python
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: | |
def __init__(self): | |
self.conn: Optional[sqlite3.Connection] = None | |
async def connect(self): | |
try: | |
self.conn = sqlite3.connect(FILENAME) | |
except sqlite3.Error: | |
pass | |
return self | |
@property | |
def is_connected(self) -> bool: | |
return self.conn is not None | |
@staticmethod | |
async def _fetch(cursor, mode) -> Optional[Any]: | |
if mode == "one": | |
return cursor.fetchone() | |
if mode == "many": | |
return cursor.fetchmany() | |
if mode == "all": | |
return cursor.fetchall() | |
return None | |
# fetch param only use when using SELECT | |
async def execute(self, query: str, values: Tuple = (), *, fetch: str = None) -> Optional[Any]: | |
cursor = self.conn.cursor() | |
cursor.execute(query, values) | |
data = await self._fetch(cursor, fetch) | |
self.conn.commit() | |
cursor.close() | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment