· 8 years ago · Apr 09, 2018, 07:28 PM
1import sqlite3
2
3def create_database():
4 with sqlite3.connect('all_playlists.db') as conn:
5 c = conn.cursor()
6 c.execute("""
7 CREATE TABLE IF NOT EXISTS playlists(
8 playlist_name TEXT,
9 username TEXT,
10 song_title TEXT)
11 """)
12
13
14def add_playlist(playlist_name, username, songs):
15 with sqlite3.connect('all_playlists.db') as conn:
16 c = conn.cursor()
17 for song in songs:
18 c.execute("""
19 INSERT INTO playlists VALUES (?, ?, ?)
20 """, (playlist_name, username, song))
21
22
23def get_all_playlists(username):
24 with sqlite3.connect('all_playlists.db') as conn:
25 c = conn.cursor()
26 c.execute("""
27 SELECT DISTINCT playlist_name
28 FROM playlists
29 WHERE username = ?
30 """, (username,))
31 return c.fetchall()
32
33
34if __name__ == '__main__':
35 create_database()
36 # Add some users and songs
37 add_playlist('happy times', 'John Smith', ['Song A', 'Song B'])
38 add_playlist('sad times', 'John Smith', ['Song C', 'Song D'])
39 add_playlist('something else', 'John Smith', ['Song E', 'Song F',
40 'Song G'])
41 add_playlist('running out of ideas', 'Janet', ['Song F', 'Song G',
42 'Song H'])
43
44 # Get playlists of John Smith
45 print("John Smith's playlists are: ", get_all_playlists('John Smith'))
46
47 # Get Janet's
48 print("Janet's playlists are: ", get_all_playlists('Janet'))