Skip to content

Instantly share code, notes, and snippets.

@lazuee
Created April 16, 2023 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazuee/5ef4ac842021d1ed7d9363fadaf143ba to your computer and use it in GitHub Desktop.
Save lazuee/5ef4ac842021d1ed7d9363fadaf143ba to your computer and use it in GitHub Desktop.
SQLite3 Database for python
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