Advertisement
sphinx2001

Python sqlite3 notebook

Dec 20th, 2020
639
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 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. db = DB("my_notes.db")
  56. print("SELECT notes #1")
  57. db.read_notes()
  58. db.add_note('2020-12-20 9:00:00',
  59.             'Выучить python!',
  60.             "Изучить python3 и написать новый гугл")
  61. print("SELECT notes #2")
  62. db.read_notes()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement