Advertisement
Guest User

DATABASE.py

a guest
May 13th, 2022
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. import sqlite3
  2.  
  3. __connection = None
  4.  
  5.  
  6. def get_connection():
  7.     global __connection
  8.     if __connection is None:
  9.         __connection = sqlite3.connect("database.db", check_same_thread = False)
  10.     return __connection
  11.  
  12.  
  13. def init_db(force: bool = False):
  14.     conn = get_connection()
  15.     c = conn.cursor()
  16.     if force:
  17.         c.execute("DROP TABLE IF EXISTS users_subs")
  18.     c.execute("""
  19. CREATE TABLE IF NOT EXISTS users_subs (
  20.    id INTEGER PRIMARY KEY,
  21.    user_id INTEGER NOT NULL,
  22.    name_sub_service TEXT NOT NULL,
  23.    date_sub TEXT NOT_NULL,
  24.    summ_sub INTEGER NOT NULL,
  25.    period_sub INTEGER NOT NULL,
  26.    finish_sub TEXT NOT NULL,
  27.    notify_date_sub TEXT NOT NULL
  28. )    
  29. """)
  30.     conn.commit()
  31.  
  32.  
  33. def add_sub_data(user_id: int, name_sub_service: str, date_sub: str, summ_sub: int, period_sub: int, finish_sub: str, notify_date_sub: str):
  34.     conn = get_connection()
  35.     c = conn.cursor()
  36.     c.execute("INSERT INTO users_subs (user_id, name_sub_service, date_sub, summ_sub, period_sub, finish_sub, notify_date_sub) VALUES(?, ?, ?, ?, ?, ?, ?)", (user_id, name_sub_service, date_sub, summ_sub, period_sub, finish_sub, notify_date_sub))
  37.     conn.commit()
  38.  
  39.  
  40. def user_exist(user_id):
  41.     conn = get_connection()
  42.     c = conn.cursor()
  43.     info = c.execute("SELECT * FROM users_subs WHERE user_id = ?", (user_id,))
  44.     if info.fetchone() is None:
  45.         return False
  46.     else:
  47.         return True
  48.  
  49. def list_subs(user_id: int, limit: int = 10000):
  50.     conn = get_connection()
  51.     c = conn.cursor()
  52.     c.execute("SELECT name_sub_service, date_sub, summ_sub, period_sub FROM users_subs WHERE user_id = ? ORDER BY id DESC LIMIT ?", (user_id, limit))
  53.     return c.fetchall()
  54.  
  55.  
  56. if __name__ == "__main__":
  57.     init_db()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement