Advertisement
alekssamos

phrasesStorage.py

Dec 24th, 2023
1,122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | Source Code | 0 0
  1. import sqlite3
  2.  
  3. class PhrasesStorage():
  4.     dbfile = "phrases.db"
  5.     def __init__(self):
  6.         with sqlite3.connect(self.dbfile) as conn:
  7.             cursor = conn.cursor()
  8.             cursor.execute("""CREATE TABLE IF NOT EXISTS phrases
  9.            (id INTEGER PRIMARY KEY, phrase TEXT)
  10.            """)
  11.  
  12.     def editPhrase(self, id, new_text):
  13.         with sqlite3.connect(self.dbfile) as conn:
  14.             cursor = conn.cursor()
  15.             cursor.execute("UPDATE phrases SET phrase=? WHERE id=?", (new_text, id,))
  16.             conn.commit()
  17.             return True
  18.  
  19.     def getPhrases(self, id=None):
  20.         with sqlite3.connect(self.dbfile) as conn:
  21.             cursor = conn.cursor()
  22.             if id is None:
  23.                 cursor.execute("SELECT * FROM phrases")
  24.             else:
  25.                 cursor.execute("SELECT * FROM phrases WHERE id=?", [(id)])
  26.             return cursor.fetchall()
  27.  
  28.     def addPhrase(self, text):
  29.         with sqlite3.connect(self.dbfile) as conn:
  30.             cursor = conn.cursor()
  31.             cursor.execute("INSERT INTO phrases (phrase) VALUES (?)", (text,))
  32.             conn.commit()
  33.             return True
  34.  
  35.     def deletePhrase(self, id):
  36.         with sqlite3.connect(self.dbfile) as conn:
  37.             cursor = conn.cursor()
  38.             cursor.execute("DELETE FROM phrases WHERE id=?", [(id),])
  39.             conn.commit()
  40.             return True
  41.  
  42.  
  43. def main():
  44.     ps = PhrasesStorage()
  45.     ps.addPhrase("Привет")
  46.     ps.addPhrase("Как дела")
  47.     ps.addPhrase("Что делаешь")
  48.     phrases = ps.getPhrases()
  49.     ps.deletePhrase( phrases[1][0] )
  50.     phrases = ps.getPhrases()
  51.     ps.editPhrase( phrases[-1][0], "Как поживаешь?" )
  52.     phrases = ps.getPhrases()
  53.     for p in phrases:
  54.         print(p[0], p[1])
  55.  
  56. if __name__ == "__main__":
  57.     main()
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement