sphinx2001

SQLite3 - 3 урок

Dec 26th, 2020 (edited)
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.87 KB | None | 0 0
  1. import sqlite3
  2. from sqlite3 import Error
  3.  
  4. class DB:
  5.     def __init__(self, dbname):
  6.         try:
  7.             self.connect = sqlite3.connect(dbname)
  8.             self.cursor = self.connect.cursor()
  9.         except Error:
  10.             print("Ошибка подключения к базе данных")
  11.         else:
  12.             print(f"connect to {dbname}")
  13.  
  14.     def table_is_exist(self, table_name):
  15.         sql = f"""SELECT name
  16.                FROM sqlite_master
  17.                WHERE type='table' AND name='{table_name}';"""
  18.         self.cursor.execute(sql)
  19.         rows = self.cursor.fetchall()
  20.         return len(rows) == 1
  21.  
  22.     def create_tables(self):
  23.         if not self.table_is_exist('notes'):
  24.             sql = """
  25.                CREATE table notes(
  26.                    id integer PRIMARY KEY AUTOINCREMENT,
  27.                    date_note datetime,
  28.                    title text,
  29.                    note_text text,
  30.                    is_done integer
  31.                );
  32.            """
  33.             self.cursor.execute(sql)
  34.  
  35.     def add_note(self, date_note, title, note_text):
  36.         sql = """
  37.            INSERT INTO notes(date_note,
  38.            title,
  39.            note_text)
  40.            VALUES(?, ?, ?)
  41.        """
  42.         self.cursor.execute(sql, (date_note, title, note_text))
  43.         self.connect.commit()
  44.  
  45.  
  46.     def read_notes(self):
  47.         sql = """SELECT id, date_note, title, note_text, is_done
  48.        FROM notes
  49.        """
  50.         self.cursor.execute(sql)
  51.         rows = self.cursor.fetchall()
  52.         for row in rows:
  53.             print(row)
  54.  
  55.     def delete_record(self, id_record):
  56.         if type(id_record) == type(1):
  57.             sql = f"""DELETE FROM notes WHERE id = {id_record}
  58.            """
  59.             self.cursor.execute(sql)
  60.             self.connect.commit()
  61.         else:
  62.             print("Тип параметра не число! Хакер чтоли?")
  63.  
  64.     def note_done(self, id_record):
  65.         if type(id_record) == type(1):
  66.             sql = f"""UPDATE notes
  67.                SET is_done = 1
  68.                WHERE id = ?
  69.            """
  70.             self.cursor.execute(sql, [id_record])
  71.             self.connect.commit()
  72.         else:
  73.             print("Тип параметра не число! Хакер чтоли?")
  74.  
  75.     def show_notes(self, is_done):
  76.         if is_done:
  77.             sql = """SELECT * FROM notes WHERE is_done = 1
  78.            """
  79.             print("Выполненные задачи")
  80.         else:
  81.             sql = """SELECT * FROM notes WHERE
  82.                            is_done = 0
  83.                            OR is_done IS Null
  84.            """
  85.             print("Не выполненные задачи")
  86.  
  87.         self.cursor.execute(sql)
  88.         rows = self.cursor.fetchall()
  89.         for row in rows:
  90.             print(row[0], row[2])
  91.  
  92.     def update_record(self):
  93.         pass
  94.  
  95.  
  96.  
  97. db = DB("my_notes.db")
  98. #db.create_tables()
  99.  
  100. # db.note_done(2)
  101.  
  102. # db.delete_record(5)
  103. #print("SELECT notes #1")
  104. #db.read_notes()
  105. #db.add_note('2020-12-23 9:00:00',
  106. #            'Нарядить елку!',
  107. #            "Купить игрушки и нарядить елку")
  108. #db.add_note('2020-12-22 9:00:00',
  109. #            'Захватить мир!',
  110. #            "Стать повелителем планеты Земля!")
  111.  
  112. #print("SELECT notes #2")
  113. #db.read_notes()
  114. #db.show_notes(True)
  115. #db.show_notes(False)
  116. def help():
  117.     print("Notebook on sqlite3 version 1.0a")
  118.     commands = {'help': 'Эта помощь',
  119.                 'quit': 'Выход из программы',
  120.                 'show doned': 'Показать выполненые записи.',
  121.                 'show undoned': 'Показать не выполненые записи.',
  122.                 'add': 'Добавление новой записи.',
  123.                 'done': 'Пометить задачу по id как выполненную',
  124.                 'del IDnum': 'Удаление записи по IDnum'
  125.                 }
  126.  
  127.     for key in commands.keys():
  128.         print(f"\t{key} - '{commands[key]}'")
  129.  
  130.  
  131. command = ""
  132. while command != 'quit':
  133.     command = input("command: ")
  134.     if command == 'help':
  135.         help()
  136.     elif command == 'show doned':
  137.         db.show_notes(True)
  138.     elif command == 'show undoned':
  139.         db.show_notes(False)
  140.     elif command == 'add':
  141.         date = input('Введите дату заметки в формате "YYYY-MM-DD H:M:S":')
  142.         title = input('Заголовок сообщения:')
  143.         text = input('Текст сообщения:')
  144.         db.add_note(date, title, text)
  145.     elif command == 'done':
  146.         id = int(input('ID задачи для выполнения:'))
  147.         db.note_done(id)
  148.     elif command.split()[0] == 'del':
  149.         db.delete_record(int(command.split()[-1]))
  150. else:
  151.     print("Bye!")
  152.  
Add Comment
Please, Sign In to add comment